Mipangilio ya Sampuli ya JavaScript ya Sampuli ya 15

Kifungu kilichoandikwa na:
  • Matukio ya Makala
  • Imeongezwa: Mar 06, 2012

Maelezo ya haraka juu ya JavaScript

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.

JavaScript ni nini?

Kuna video ya zamani ya YouTube inayojibu swali vizuri. Hapa inakwenda.

Vidokezo vya mwanzoni: Nini unahitaji kujua?

Kwa mwanzo, misingi ya chini unayohitaji kujua ni:

  • JavaScript can be turned off in the browser
  • JavaScript will run each time a page is loaded
  • JavaScript takes time to load on a slow Internet connection
  • JavaScript is still ran from cached pages
  • You can host JavaScript within a web page or externally from a .js file
  • JavaScript is completely different than 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). 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 your website.

  • Is JavaScript required for the site to function properly?
  • What will the site look like if the JavaScript was blocked?
  • Will the JavaScript harm the server performance?
  • Will adding the JavaScript help move your site in the direction you want it to go?

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 For Your Website

Jarida la JavaScript

Now, let’s get down to the stuffs that you came here for – below is a list of 15 JavaScript snippets that will enhance your site in either functionality or appearance. The code will be broken down into two sections, the head and body or .js file. If no section title is given then it is not needed for that particular snippet.

Understanding HTML5 Video

Mfano wa haraka

<script type="text/javascript">

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

if ( !understands_video() ) {
// Lazima kuwa kivinjari kikuu au IE.
// Maybe do something like hide custom
// HTML5 udhibiti. Au chochote ...
videoControls.style.display = ‘none’;
}

</ Script>

Snippet ya JavaScript inafanya nini?

This little snippet will prevent your website from trying to display a video that the browser cannot support, saving you bandwidth and processing power.

JavaScript Cookies

Mfano wa haraka

<script type="text/javascript">

/ **

Inaweka Cookie kwa jina na thamani.

*

jina la jina la cookie

* Thamani Thamani ya kuki

* [huisha] Tarehe ya kumalizika ya kuki (default: mwisho wa kikao cha sasa)

* [njia] Njia ambapo kuki ni halali (default: njia ya wito hati)

* [uwanja] Domain ambapo cookie halali

* (default: uwanja wa hati ya wito)

* [salama] thamani ya Boolean inayoonyesha kama maambukizi ya coo inahitaji

* maambukizi salama

*/

tengeneza setCookie (jina, thamani, muda, njia, uwanja, salama) {

document.cookie = jina + "=" + kutoroka (thamani) +

(inamalizika)? "; itaisha =" + imekwisha muda.toGMTString (): "") +

(? (Njia) "; njia =" + njia: "") +

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

((Kupata) "; salama": "");

}

</ Script>

<script type="text/javascript">

/ **

* Inapata thamani ya cookie maalum.

*

Jina la jina la kuki inayotaka.

*

* Inarudi kamba yenye thamani ya cookie maalum,

* au null ikiwa cookie haipo.

*/

tumia getCookie (jina) {

var dc = document.cookie;

var kiambishi = jina + "=";

var kuanza = dc.indexOf (";" + kiambishi);

ikiwa (kuanza == -1) {

kuanza = dc.indexOf (kiambishi);

ikiwa (kuanza! = 0) kurudi null;

} Mwingine {

kuanza + = 2;

}

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

ikiwa (mwisho == -1) {

mwisho = dc.length;

}

kurudi unescape (dc.substring (kuanza + prefix.length, mwisho));

}

</ Script>

<script type="text/javascript">

/ **

* Inafuta cookie maalum.

*

Jina la jina la kuki

* [njia] njia ya kuki (lazima iwe sawa na njia inayotumiwa kuunda kuki)

* domain [domain] ya kuki (lazima sawa na domain kutumika kujenga cookie)

*/

futa deleteCookie (jina, njia, kikoa) {

ikiwa (kupataCookie (jina)) {

document.cookie = jina + "=" +

(? (Njia) "; njia =" + njia: "") +

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

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

}

}

</ Script>

Snippet ya JavaScript inafanya nini?

This snippet is a little long but very useful, it will allow your site to store information on the viewer’s computer then read it at another point in time. This snippet can be used in many different ways to accomplish different tasks.

Preload your images

Mfano wa haraka

<script type="text/javascript">

var images = safu mpya ();

kazi preloadImages () {

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

picha [i] = picha mpya ();

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

}

}

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

</ Script>

Snippet ya JavaScript inafanya nini?

This snippet will prevent your site from having that awkward time when it is only displaying part of the site; this not only looks bad but is also unprofessional. All you have to do is add your images to the preloadImages section and you are ready to roll.

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)){
kurudi (kweli);
}
alert("Invalid e-mail address! Please enter again carefully!.");
kurudi (uongo);
}
</ Script>

Mwili:

<form onSubmit="return validateEmail(this);" action="">
Anuani ya Barua pepe:
<input type="text" name="emailid" />
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</ Fomu>

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.

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) {
hati.Kuondoa (Tukio.MOUSEDOWN);
document.onmousedown = f1;
}
mwingine {
document.onmouseup = f2;
document.oncontextmenu = f1;
}
document.oncontextmenu = new function("return false");
</ Script>

Snippet ya JavaScript inafanya nini?

This snippet will prevent the viewer from being able to right-click on your page. This can discourage the average user from borrow images or code from your site.

Onyesha Quotes Random

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);
hati.write (quotes [rand]);
}
AndikaRandomQuote ();
</ Script>

Mwili:

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

Snippet ya JavaScript inafanya nini?

Ok so this is not a snippet that all sites would use but it can be used to display more than just random quotes. You can change the content ok the quotes to whatever you want and have random images or text displayed anywhere on your site.

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?

This snippet is great if you have multiple pages on an article or tutorial. It will allow the user the browse between the pages with ease. It is also small and light weight from a resource point of view.

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?

This snippet will allow the user to bookmark your page with ease; all they have to do is click the link. Its little features like this that can increase your viewers overall experience.

Muunganisho wa Kwanza wa Ukurasa wa Kwanza

Mfano wa haraka

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

Snippet ya JavaScript inafanya nini?

This little link will allow your views to easily print your page. It utilizes the quick print feature already setup by your browser and utilizes no resources until it is clicked.

Onyesha tarehe iliyopangwa

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?

This snippet will allow you to display the current date anywhere on your webpage and does not need to be updated. Simply put it in place and forget about it.

Separator ya Comma

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;
hati.write (nje);
}
</ Script>

Mwili:

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

Snippet ya JavaScript inafanya nini?

This snippet would be used mainly by sites that use numbers often. This snippet will keep your numbers looking the same across the board. All you have to do is copy the body line where you want to add a number and replace the number there with your number.

Pata Eneo la Kuonyesha la Kivinjari

Mfano wa haraka

<script type="text/javascript">

<! -

var viewportwidth;

var viewportheight;

// viwango vya zaidi vinavyolingana (mozilla / netscape / opera / IE7) tumia window.innerWidth na window.innerHeight

kama (typeof window.innerWidth! = 'isiyojulikana')

{

viewportwidth = window.innerWidth,

viewportheight = window.innerHeight

}

// IE6 katika viwango vinavyolingana (yaani kwa mafundisho halali kama mstari wa kwanza katika waraka)

mwingine kama (aina ya hati.documentElement! = 'undefined'

&& aina ya hati.documentElement.clientWidth! =

'haijulikani' && hati.documentElement.clientWidth! = 0)

{

viewportwidth = hati.documentElement.clientWidth,

viewportheight = hati.documentElement.clientHeight

}

// matoleo ya zamani ya IE

mwingine

{

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

viewportheight = hati.getElementsByTagName ('mwili') [0] .clientHeight

}

hati.write ('<p> Upana wako wa upangilio ni' + viewportwidth + 'x' + viewportheight + '</ p>');

// ->

</ Script>

Snippet ya JavaScript inafanya nini?

This snippet will allow you to get the width and height of the display area in your views browser. This will give the designer the ability to create and use different displays based on the size of the user’s browser window.

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?

This snippet will allow you to redirect your viewers to another page and it has the option of setting a delay. The use of this snippet is pretty self-explanatory and it is a very valuable tool to have in your belt.

Detect iPhones

Sampuli

<script type="text/javascript">

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

ikiwa (hati.cookie.indexOf ("iphone_redirect = uongo") == -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.

Print Message to Status Bar

Mfano wa haraka

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

Snippet ya JavaScript inafanya nini?

This little snippet will allow you to print a message to the status bar. You can display recent or important news in an area the will catch the eye of the user.

Kifungu cha Guest Guest WHSR

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

Pata kushikamana: