Programmers must know 35 jQuery code snippets, and programmers must know 35 jquery

Source: Internet
Author: User

Programmers must know 35 jQuery code snippets, and programmers must know 35 jquery

JQuery has now become the most popular JavaScript library in Web development. With jQuery and a large number of plug-ins, you can easily achieve a variety of brilliant results. This article will introduce some practical jquery skills, hoping to help you use jQuery more efficiently.

The collection of 35 jQuery Tips/code snippets can help you develop quickly.

1. Right-click prohibited

$(document).ready(function(){  $(document).bind("contextmenu",function(e){    return false;  });});

2. Hide text in the search text box

Hide when clicked in the search field, the value.(example can be found below in the comment fields)$(document).ready(function() {$("input.text1").val("Enter your search text here");  textFill($('input.text1'));});  function textFill(input){ //input focus text function   var originalvalue = input.val();   input.focus( function(){     if( $.trim(input.val()) == originalvalue ){ input.val(''); }   });   input.blur( function(){     if( $.trim(input.val()) == '' ){ input.val(originalvalue); }   });}

3. Open the link in a new window

XHTML 1.0 Strict doesn't allow this attribute in the code, so use this to keep the code valid.$(document).ready(function() {  //Example 1: Every link will open in a new window  $('a[href^="http://"]').attr("target", "_blank");  //Example 2: Links with the rel="external" attribute will only open in a new window  $('a[@rel$='external']').click(function(){   this.target = "_blank";  });});// how to use<a href="http://www.opensourcehunter.com" rel=external>open link</a>

4. Check the browser

Note: In jQuery 1.4, $. support replaced the $. browser variable.

$(document).ready(function() {// Target Firefox 2 and aboveif ($.browser.mozilla && $.browser.version >= "1.8" ){  // do something}// Target Safariif( $.browser.safari ){  // do something}// Target Chromeif( $.browser.chrome){  // do something}// Target Caminoif( $.browser.camino){  // do something}// Target Operaif( $.browser.opera){  // do something}// Target IE6 and belowif ($.browser.msie && $.browser.version <= 6 ){  // do something}// Target anything above IE6if ($.browser.msie && $.browser.version > 6){  // do something}});

5. Pre-load images

This piece of code will prevent the loading of all images, which can be useful if you have a site with lots of images.$(document).ready(function() {jQuery.preloadImages = function(){ for(var i = 0; i<ARGUMENTS.LENGTH; jQuery(?

6. Page Style Switching

$(document).ready(function() {  $("a.Styleswitcher").click(function() {    //swicth the LINK REL attribute with the value in A REL attribute    $('link[rel=stylesheet]').attr('href' , $(this).attr('rel'));  });// how to use// place this in your header<LINK rel=stylesheet type=text/css href="default.css">// the links<A href="#" rel=default.css>Default Theme</A><A href="#" rel=red.css>Red Theme</A><A href="#" rel=blue.css>Blue Theme</A>});

7. The column height is the same

If two CSS columns are used, the height of the two columns can be the same.

$(document).ready(function() {function equalHeight(group) {  tallest = 0;  group.each(function() {    thisHeight = $(this).height();    if(thisHeight > tallest) {      tallest = thisHeight;    }  });  group.height(tallest);}// how to use$(document).ready(function() {  equalHeight($(".left"));  equalHeight($(".right"));});});

8. dynamically control the page font size

You can change the page font size.

$(document).ready(function() { // Reset the font size(back to default) var originalFontSize = $('html').css('font-size');  $(".resetFont").click(function(){  $('html').css('font-size', originalFontSize); }); // Increase the font size(bigger font0 $(".increaseFont").click(function(){  var currentFontSize = $('html').css('font-size');  var currentFontSizeNum = parseFloat(currentFontSize, 10);  var newFontSize = currentFontSizeNum*1.2;  $('html').css('font-size', newFontSize);  return false; }); // Decrease the font size(smaller font) $(".decreaseFont").click(function(){  var currentFontSize = $('html').css('font-size');  var currentFontSizeNum = parseFloat(currentFontSize, 10);  var newFontSize = currentFontSizeNum*0.8;  $('html').css('font-size', newFontSize);  return false; });});

9. Return to the top of the page

For a smooth(animated) ride back to the top(or any location).$(document).ready(function() {$('a[href*=#]').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {  var $target = $(this.hash);  $target = $target.length && $target  || $('[name=' + this.hash.slice(1) +']');  if ($target.length) { var targetOffset = $target.offset().top; $('html,body') .animate({scrollTop: targetOffset}, 900);  return false;  } } });// how to use// place this where you want to scroll to<A name=top></A>// the link<A href="#top">go to top</A>});

10. Obtain the XY value of the mouse pointer.

Want to know where your mouse cursor is?$(document).ready(function() {  $().mousemove(function(e){   //display the x and y axis values inside the div with the id XY  $('#XY').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY); });// how to use<DIV id=XY></DIV>});

11. Return to the top button

You can use animate and scrollTop to return the animation at the top, without using other plug-ins.

// Back to top$('a.top').click(function () { $(document.body).animate({scrollTop: 0}, 800); return false;});<!-- Create an anchor tag --><a href="#">Back to top</a>

Changing the scrollTop value can adjust the return distance from the top, while the second parameter of animate is the time required to execute the Return Action (unit: milliseconds ).

12. Pre-load images

If your page uses a lot of invisible images (such as hover display), you may need to pre-load them:

$.preloadImages = function () { for (var i = 0; i < arguments.length; i++) {  $('').attr('src', arguments[i]); }};$.preloadImages('img/hover1.png', 'img/hover2.png');

13. Check whether the image is loaded.

Sometimes you need to make sure that the image is loaded to perform the following operations:

$('img').load(function () { console.log('image load successful');});

You can replace img with another ID or class to check whether the specified image is loaded.

14. Automatically modify damaged Images

If you happen to find broken image links on your website, you can replace them with images that are not easy to replace. Adding this simple code can save a lot of trouble:

$('img').on('error', function () { $(this).prop('src', 'img/broken.png');});

Even if your website does not have broken image links, adding this code is harmless.

15. hover the mouse over (hover) to switch the class attribute

If you want to change the effect when hovering over a clickable element, the following code adds the class attribute when hovering over the element, when you move the mouse away, the class attribute is automatically canceled:

$ ('. Btn '). hover (function () {$ (this ). addClass ('hover ');}, function () {$ (this ). removeClass ('hover ') ;}); you only need to add necessary CSS code. If you want more concise code, you can use the toggleClass method: $ ('. btn '). hover (function () {$ (this ). toggleClass ('hover ');});

Note: directly using CSS to achieve this effect may be a better solution, but you still need to know this method.

16. Disable the input field

Sometimes you may need to disable the form's submit button or an input field until the user performs some operations (for example, check the "read terms" check box ). You can add the disabled attribute until you want to enable it:

$ ('Input [type = "submit"] '). prop ('Disabled', true );
All you need to do is execute the removeAttr method and pass the attribute to be removed as a parameter:
$ ('Input [type = "submit"] '). removeAttr ('Disabled ');

17. Stop link Loading

Sometimes you don't want to link to a page or reload it. You may want it to do something else or trigger some other scripts. You can do this:

$('a.no-link').click(function (e) { e.preventDefault();});

18. Switch between fade and slide

Fade and slide are the animation effects we often use in jQuery. They can make the element display better. However, if you want to use the first effect when the element is displayed and the second effect when it disappears, you can do this:

// Fade$('.btn').click(function () { $('.element').fadeToggle('slow');});// Toggle$('.btn').click(function () { $('.element').slideToggle('slow');});

19. Simple accordion Effect

This is a quick and easy way to achieve the accordion effect:

// Close all panels$('#accordion').find('.content').hide();// Accordion$('#accordion').find('.accordion-header').click(function () { var next = $(this).next(); next.slideToggle('fast'); $('.content').not(next).slideUp('fast'); return false;});

20. Make the two divs have the same height

Sometimes you need to make the two divs have the same height regardless of the content in them. You can use the following code snippet:

var $columns = $('.column');var height = 0;$columns.each(function () { if ($(this).height() > height) {  height = $(this).height(); }});$columns.height(height);

This code loops through a group of elements and sets their height to the maximum height in the element.

21. verify whether the element is null

This will allow you to check if an element is empty.$(document).ready(function() { if ($('#id').html()) {  // do something  }});

22. Replace Element

$(document).ready(function() {  $('#id').replaceWith('<DIV>I have been replaced</DIV>');});

23. jQuery delayed Loading Function

$(document).ready(function() {  window.setTimeout(function() {   // do something  }, 1000);});

24. Remove words

$(document).ready(function() {  var el = $('#id');  el.html(el.html().replace(/word/ig, ""));});

25. verify whether the element exists in the jquery object set

$(document).ready(function() {  if ($('#id').length) { // do something }});

26. Make the entire DIV clickable

$(document).ready(function() {  $("div").click(function(){   //get the url from href attribute and launch the url   window.location=$(this).find("a").attr("href"); return false;  });// how to use<DIV><A href="index.html">home</A></DIV>});

27. Conversion between ID and Class

When the Window size is changed, switch between ID and Class

$(document).ready(function() {  function checkWindowSize() {  if ( $(window).width() > 1200 ) {    $('body').addClass('large');  }  else {    $('body').removeClass('large');  }  }$(window).resize(checkWindowSize);});

28. Clone object

$(document).ready(function() {  var cloned = $('#id').clone();// how to use<DIV id=id></DIV>});

29. Place elements in the center of the screen

$(document).ready(function() { jQuery.fn.center = function () {   this.css("position","absolute");   this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");   this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");   return this; } $("#id").center();});

30. Write your own Selector

$(document).ready(function() {  $.extend($.expr[':'], {    moreThen1000px: function(a) {      return $(a).width() > 1000;   }  }); $('.box:moreThen1000px').click(function() {   // creating a simple js alert box   alert('The element that you have clicked is over 1000 pixels wide'); });});

31. count the number of elements

$(document).ready(function() {  $("p").size();});

32. Use your own Bullets

$(document).ready(function() {  $("ul").addClass("Replaced");  $("ul > li").prepend("‒ "); // how to use ul.Replaced { list-style : none; }});

33. Reference The Jquery class library on the Google host

//Example 1<SCRIPT src="http://www.google.com/jsapi"></SCRIPT><SCRIPT type=text/javascript>google.load("jquery", "1.2.6");google.setOnLoadCallback(function() {  // do something});</SCRIPT><SCRIPT type=text/javascript src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></SCRIPT> // Example 2:(the best and fastest way)<SCRIPT type=text/javascript src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></SCRIPT>

34. Disable Jquery (animation) Effects

$(document).ready(function() {  jQuery.fx.off = true;});

35. Conflict Solution with other Javascript Class Libraries

$(document).ready(function() {  var $jq = jQuery.noConflict();  $jq('#id').show();});

The above content is the 35 jQuery code snippets that programmers will share with you. I hope you will like them.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.