Mfano wa 15 wa bure wa JavaScript kwa Wavuti zako

Kifungu kilichoandikwa na:
  • Matukio ya Makala
  • Iliyasasishwa Septemba 23, 2019

JavaScript is used everywhere online these days – to improve website interactivity, to validate information, and/or to improve a website outlooks.

JavaScript first appeared in 1995 and has come a long way since then in terms of being accepted and how it is used. The syntax used in JavaScript was strongly influenced by C; but Java, Pearl, Python, and Scheme also played its part too.

JavaScrip Beginner Tips: What You Need To Know?

Kwa mwanzo, misingi ya chini unayohitaji kujua ni:

  • JavaScript inaweza kuzima kwenye kivinjari
  • JavaScript itaendesha kila wakati ukurasa umebeba
  • JavaScript inachukua muda wa kupakia uunganisho wa polepole wa Intaneti
  • JavaScript bado imekimbia kutoka kurasa zilizofichwa
  • Unaweza mwenyeji wa JavaScript ndani ya ukurasa wa wavuti au nje kutoka kwa faili ya .js
  • JavaScript ni tofauti kabisa na Java

It is also important to understand that JavaScript will actually lead to disaster when it's used in a wrong way.

Poorly configured and sloppy coded JavaScripts will slow your website and damage the overall site navigation. This in turn affect the return rate of your visitors (due to bad user experience) as well as search engine rankings (due to slow website response rates and bot crawling). To help validate my case here, put yourself in the shoes of a viewer. If a website you were visiting loaded slowly, was difficult to navigate, and in overall, unappealing – would you return to the site? I wouldn’t.

Below is a small list of things to think about when adding JavaScript to tovuti yako.

  • Javascript inahitajika ili tovuti itafanya kazi vizuri?
  • Tovuti itaonekanaje kama JavaScript imefungwa?
  • Je JavaScript itaumiza utendaji wa seva?
  • Je, utaongeza usaidizi wa Javascript kuhamisha tovuti yako kwa uongozi unayotaka?

No, I am not trying to scare you away with these points.

In fact, don’t be afraid to use JavaScript on your websites as it provides tons benefits and, as mentioned, it's used by the majorities. The key point I am trying to get across here is don’t just keep adding JavaScript features to a site when they are unnecessary. Some sites are will need more JavaScript than the rest; some just need less – Just because one site is doing it doesn't mean you should do the same.

Freebies: 15 Cool JavaScript Snippets Kwa Website yako

Sasa, wacha tufike chini kwa vitu ambavyo ulikuja hapa - hapa chini kuna orodha ya vijikuta vya 15 JavaScript ambazo zitaongeza tovuti yako katika utendaji au kuonekana. Nambari hiyo itavunjika katika sehemu mbili, kichwa na mwili au faili ya .js. Ikiwa hakuna kichwa cha sehemu kinachopewa basi hazihitajike kwa snippet hiyo.

1. Understanding HTML5 Video

Mfano wa haraka

<script type="text/javascript">

function understands_video() {
return !!document.createElement('video').canPlayType; // boolean
}

if ( !understands_video() ) {
// Must be older browser or IE.
// Maybe do something like hide custom
// HTML5 controls. Or whatever...
videoControls.style.display = 'none';
}

</script>

Snippet ya JavaScript inafanya nini?

Snippet hii ndogo itazuia tovuti yako kutoka kujaribu kujaribu video ambayo kivinjari haiwezi kuunga mkono, kukuokoa bandwidth na nguvu ya usindikaji.

2. JavaScript Cookies

Mfano wa haraka

<script type="text/javascript">

/**

* Sets a Cookie with the given name and value.

*

* name       Name of the cookie

* value      Value of the cookie

* [expires]  Expiration date of the cookie (default: end of current session)

* [path]     Path where the cookie is valid (default: path of calling document)

* [domain]   Domain where the cookie is valid

*              (default: domain of calling document)

* [secure]   Boolean value indicating if the cookie transmission requires a

*              secure transmission

*/                        

function setCookie(name, value, expires, path, domain, secure) {

    document.cookie= name + "=" + escape(value) +

        ((expires) ? "; expires=" + expires.toGMTString() : "") +

        ((path) ? "; path=" + path : "") +

        ((domain) ? "; domain=" + domain : "") +

        ((secure) ? "; secure" : "");

}

</script>




<script type="text/javascript">

/**

* Gets the value of the specified cookie.

*

* name  Name of the desired cookie.

*

* Returns a string containing value of specified cookie,

*   or null if cookie does not exist.

*/

function getCookie(name) {

    var dc = document.cookie;

    var prefix = name + "=";

    var begin = dc.indexOf("; " + prefix);

    if (begin == -1) {

        begin = dc.indexOf(prefix);

        if (begin != 0) return null;

    } else {

        begin += 2;

    }

    var end = document.cookie.indexOf(";", begin);

    if (end == -1) {

        end = dc.length;

    }

    return unescape(dc.substring(begin + prefix.length, end));

}

</script>




<script type="text/javascript">

/**

* Deletes the specified cookie.

*

* name      name of the cookie

* [path]    path of the cookie (must be same as path used to create cookie)

* [domain]  domain of the cookie (must be same as domain used to create cookie)

*/

function deleteCookie(name, path, domain) {

    if (getCookie(name)) {

        document.cookie = name + "=" +

            ((path) ? "; path=" + path : "") +

            ((domain) ? "; domain=" + domain : "") +

            "; expires=Thu, 01-Jan-70 00:00:01 GMT";

    }

}

</script>

Snippet ya JavaScript inafanya nini?

Snippet hii ni muda mrefu lakini ni muhimu sana, itawawezesha tovuti yako kuhifadhi habari kwenye kompyuta ya mtazamaji kisha uisome wakati mwingine. Snippet hii inaweza kutumika kwa njia nyingi za kufanikisha kazi tofauti.

3. Preload your images

Mfano wa haraka

<script type="text/javascript">

var images = new Array();

function preloadImages(){

    for (i=0; i < preloadImages.arguments.length; i++){

         images[i] = new Image();

        images[i].src = preloadImages.arguments[i];

    }

}

preloadImages("logo.jpg", "main_bg.jpg", "body_bg.jpg", "header_bg.jpg");

</script>

Snippet ya JavaScript inafanya nini?

Snippet hii itauzuia tovuti yako kuwa na wakati usio wakati usioonyesha tu sehemu ya tovuti; hii sio tu inaonekana mbaya bali pia haina faida. Wote unapaswa kufanya ni kuongeza picha zako kwenye sehemu ya preloadImages na uko tayari kuingia.

4. E-mail Validation

Mfano wa haraka

kichwa:

<script type="text/javascript">
function validateEmail(theForm) {
if (/^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/.test(theForm.email-id.value)){
return(true);
}
alert("Invalid e-mail address! Please enter again carefully!.");
return(false);
}
</script>

Mwili:

<form onSubmit="return validateEmail(this);" action="">
E-mail Address:
<input type="text" name="emailid" />
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</form>

Snippet ya JavaScript inafanya nini?

This snippet will validate that a properly formatted e-mail address is entered in a form, it cannot guarantee that the e-mail address is real, there is no way to check for that with JavaScript.

5. No Right-Click

Mfano wa haraka

<script type="text/javascript">
function f1() {
  if(document.all) { return false; }
}
function f2(e) {
  if(document.layers || (document.getElementById &! document.all)) {
    if(e.which==2 || e.which==3) { return false; }
  }
}
if(document.layers) {
  document.captureEvents(Event.MOUSEDOWN);
  document.onmousedown = f1;
}
else {
  document.onmouseup = f2;
  document.oncontextmenu = f1;
}
document.oncontextmenu = new function("return false");
</script>

Snippet ya JavaScript inafanya nini?

Snippet hii itawazuia mtazamaji kuwa na uwezo wa kubofya haki kwenye ukurasa wako. Hii inaweza kudhoofisha mtumiaji wastani wa kukopa picha au msimbo kutoka kwenye tovuti yako.

6. Display Random Quotes

Mfano wa haraka

Kichwa:

<script type="text/javascript">
  writeRandomQuote = function () {
    var quotes = new Array();
    quotes[0] = "Action is the real measure of intelligence.";
    quotes[1] = "Baseball has the great advantage over cricket of being sooner ended.";
    quotes[2] = "Every goal, every action, every thought, every feeling one experiences, whether it be consciously or unconsciously known, is an attempt to increase one's level of peace of mind.";
    quotes[3] = "A good head and a good heart are always a formidable combination.";
    var rand = Math.floor(Math.random()*quotes.length);
    document.write(quotes[rand]);
  }
  writeRandomQuote();
</script>

Mwili:

<script type="text/javascript">writeRandomQuote();</script>

Snippet ya JavaScript inafanya nini?

Ok hivyo hii sio snippet ambayo maeneo yote yatatumia lakini inaweza kutumika kuonyesha zaidi ya quotes tu. Unaweza kubadilisha yaliyomo vyema kila kitu unachotaka na uwe na picha za random au maandiko yaliyoonyeshwa mahali popote kwenye tovuti yako.

7. Previous/Next Links

Mfano wa haraka

<a href="javascript:history.back(1)">Previous Page</a> | <a href="javascript:history.back(-1)">Next Page</a>

Snippet ya JavaScript inafanya nini?

Snippet hii ni nzuri ikiwa una kurasa nyingi kwenye makala au mafunzo. Itawawezesha mtumiaji kuvinjari kati ya kurasa kwa urahisi. Pia ni uzito mdogo na mwembamba kutoka kwa mtazamo wa rasilimali.

8. Bookmark a Page

Mfano wa haraka

<a href="javascript:window.external.AddFavorite('http://www.yoursite.com', 'Your Site Name')">Add to Favorites</a>

Snippet ya JavaScript inafanya nini?

Snippet hii itawawezesha mtumiaji kufungua ukurasa wako kwa urahisi; wote wanapaswa kufanya ni bonyeza kiungo. Makala yake ndogo kama hii ambayo inaweza kuongeza watazamaji wako uzoefu kamili.

9. Easy Print Page Link

Mfano wa haraka

<a href="javascript:window.print();">Print Page</a>

Snippet ya JavaScript inafanya nini?

Kiunganisho hiki kidogo kitaruhusu maoni yako kwa urahisi kuchapisha ukurasa wako. Inatumia kipengele cha kuchapisha haraka kilichowekwa tayari na kivinjari chako na haitumii rasilimali mpaka kinapobofya.

10. Show Formatted Date

Mfano wa haraka

Kichwa:

<script type="text/javascript">
  function showDate() {
    var d = new Date();
    var curr_date = d.getDate();
    var curr_month = d.getMonth() + 1; //months are zero based
    var curr_year = d.getFullYear();
    document.write(curr_date + "-" + curr_month + "-" + curr_year);
  }
</script>

Mwili:

<script type="text/javascript">showDate();</script>

Snippet ya JavaScript inafanya nini?

Snippet hii itawawezesha kuonyesha tarehe ya sasa popote kwenye ukurasa wako wa wavuti na haipaswi kuwa updated. Kuweka tu mahali na kusahau kuhusu hilo.

11. Comma Separator

Mfano wa haraka

Kichwa:

<script type="text/javascript">
function addCommas(num) {
  num += '';
  var n1 = num.split('.');
  var n2 = n1[0];
  var n3 = n1.length > 1 ? '.' + n1[1] : '';
  var temp = /(d+)(d{3})/;
  while (temp.test(n2)) {
    n2 = n2.replace(temp, '' + ',' + '');
  }
  var out = return n2 + n3;
  document.write(out);
}
</script>

Mwili:

<script type="text/javascript">addCommas("4550989023");</script>

Snippet ya JavaScript inafanya nini?

Snippet hii itatumiwa hasa na maeneo ambayo hutumia namba mara nyingi. Snippet hii itaweka namba zako zitazama sawa kwenye ubao. Wote unapaswa kufanya ni nakala ya mstari wa mwili ambapo unataka kuongeza namba na uweke nafasi ya namba pale na nambari yako.

12. Get the Display Area of a Browser

Mfano wa haraka

<script type="text/javascript">

<!--

var viewportwidth;

var viewportheight;

// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

if (typeof window.innerWidth != 'undefined')

{

      viewportwidth = window.innerWidth,

      viewportheight = window.innerHeight

}

// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

else if (typeof document.documentElement != 'undefined'

     && typeof document.documentElement.clientWidth !=

     'undefined' && document.documentElement.clientWidth != 0)

{

       viewportwidth = document.documentElement.clientWidth,

       viewportheight = document.documentElement.clientHeight

}

// older versions of IE

else

{

       viewportwidth = document.getElementsByTagName('body')[0].clientWidth,

       viewportheight = document.getElementsByTagName('body')[0].clientHeight

}

document.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');

//-->

</script>

Snippet ya JavaScript inafanya nini?

Snippet hii itawawezesha kupata upana na urefu wa eneo la kuonyesha kwenye kivinjari chako cha maoni. Hii itampa designer uwezo wa kuunda na kutumia maonyesho tofauti kulingana na ukubwa wa dirisha la kivinjari cha mtumiaji.

13. Redirect with Optional Delay

Mfano wa haraka

<script type="text/javascript">

setTimeout( "window.location.href =

'http://walkerwines.com.au/'", 5*1000 );

</script>

Snippet ya JavaScript inafanya nini?

Snippet hii itawawezesha kurejesha watazamaji wako kwenye ukurasa mwingine na ina fursa ya kuweka kuchelewa. Matumizi ya snippet hii ni nzuri sana na ni chombo muhimu sana kuwa na ukanda wako.

14. Detect iPhones

Sampuli

<script type="text/javascript">

if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {

    if (document.cookie.indexOf("iphone_redirect=false") == -1) {

        window.location = "http://m.espn.go.com/wireless/?iphone&i=COMR";

    }

}

</script>

Snippet ya JavaScript inafanya nini?

Snippet hii itawawezesha kuchunguza ikiwa mtazamaji wako kwenye iPhone au iPod inakuwezesha kuonyesha maudhui tofauti kwao. Snippet hii ni muhimu sana na soko kubwa la soko la simu na linaendelea kukua.

15. Print Message to Status Bar

Mfano wa haraka

<script language="javascript" type="text/javascript"> 
<!-- 
   window.status = "<TYPE YOUR MESSAGE>"; 
// --> 
</script>

Snippet ya JavaScript inafanya nini?

Snippet hii ndogo itawawezesha kuchapisha ujumbe kwenye bar ya hali. Unaweza kuonyesha habari za hivi karibuni au muhimu katika eneo ambalo litaona jicho la mtumiaji.

Kuhusu Guest WHSR

Makala hii imeandikwa na mchangiaji wa mgeni. Maoni ya mwandishi hapa chini ni yake mwenyewe na hawezi kutafakari maoni ya WHSR.