10 Jquery Snippets Every Developer Should Know 

10 jQuery snippets every developer should know 
by Janeth Kent Date: 13-02-2014 jquery resources tutorials tips plugins snippets webdev


For this post, we would like to share with our readers 10 JQuery Code Snippets which we’ve collected that users can copy and paste directly into their themes by which to create some nice visual effects which will spruce up your website. Enjoy !

1. Smooth Scrolling for Internal Links

$('a[href^="#"]').bind('click.smoothscroll',function (e) { 
 e.preventDefault(); 
   var anchor = this.hash,  
$target = $(target); 
   $('html, body').stop().animate({ 
 'scrollTop': $target.offset().top 
 }, 500, 'swing', function () {
  window.location.hash = anchor; 
 }); 
   });  

2. JS : jQuery Get All Nodes, Including Orphaned Text

var $element = $('#my-element'); 
var $nodes = $element.contents(); 
$nodes.each(function() {
if(this.nodeType === 3 && $.trim($(this).text())) { 
$(this).wrap('');
}
}); 

3. Select Box Restrict

$("#categories option").click(function(e){
  if ($(this).parent().val().length > 2) {
  $(this).removeAttr("selected"); 
 }  
});

4. Facebook Get User Permissions and Send These Via Ajax

// always put this function inside a click or a user action, don't automatically open it or browser will block the popup.  
$('#button_id').click(function(){  
FB.login(function(logged) {  
if(logged.status == "connected"){  
FB.api("/me", function(response) {
  $.ajax({  type: "POST",  url: "pass_value.php",  data: {
fb_id: response.id, name: response.first_name, last_name: response.last_name,
 gender: response.gender},  success: 
function(){window.location.href = "gosomewhere.php"; 
} 
 });  
});  
}  /* in the scope u specify all permission you need, in this case you get all basic INFO and pubblish to wall permission */
  }, {scope: 'publish_stream'}); 
   });

5. jQuery Remove Class with WildCard

var _c = 'your-icon-class'
$('.currency').removeClass (function (index, css) {
return (css.match (/\bicon-\S+/g) || []).join(' ');
}).addClass('icon-'+_c);

6. jQuery Toggle Disabled

/* HTML 
|
|
|
 <input type="text"value="I &lt;3 EMOTICODE <img src="http://codegeekz.com/wp-includes/images/smilies/icon_smile.gif" alt=":)" class="wp-smiley"> " />  <input type="button" value="Toggle Disabled" />
| 
|
|
*/ 
// Plugin 
(function($) { 
$.fn.toggleDisabled = function() { 
return this.each(function() { 
var $this = $(this); 
if ($this.attr('disabled')) $this.removeAttr('disabled'); 
else $this.attr('disabled', 'disabled'); 
 }); 
};  })(jQuery); 
 // TEST 
$(function() { 
  $('input:button').click(function(){ 
  $('input:text').toggleDisabled();   
});   
});

7. Smooth Scroller

// HTML:  //
  <h1 id="anchor">Lorem Ipsum</h1>
//<a class="topLink" href="#anchor">Back to Top</a>
$(document).ready(function()
{    $("a.topLink").click(function() {
$("html, body").animate({
scrollTop: $($(this).attr("href")).offset().top + "px"
},
{  duration: 500,  easing: "swing"
});  return false;
});
});

8. Form Tracking with JS and Google Analytics

var array1 = [];
$(document).ready(function () {
$('input').change(function () {
var formbox = $(this).attr('id');  array1.push(formbox);
  console.log("you filled out box " + array1);
});
$('#submit').click(function ()
{  console.log('tracked ' + array1);
 //alert('this is the order of boxes you filled out: ' + array1);
 _gaq.push(['_trackEvent', 'Form', 'completed', '"' + array1 + '"']);
});
  }); 

9. Test Password Strength

$('#pass').keyup(function(e){
var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*$", "g");
var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
var enoughRegex = new RegExp("(?=.{6,}).*", "g");
if (false == enoughRegex.test($(this).val())) {
$('#passstrength').html('More Characters');  }
else if (strongRegex.test($(this).val())) {
$('#passstrength').className = 'ok';
  $('#passstrength').html('Strong!');  }
else if (mediumRegex.test($(this).val())) {
$('#passstrength').className = 'alert';
$('#passstrength').html('Medium!');  }
else {
$('#passstrength').className = 'error'; 
$('#passstrength').html('Weak!');
}
return true;
});

10. Make Entire Div Clickable

<div class="myBox">blah blah blah.
<a href="http://google.com">link</a></div>
[/jquery]
The following lines of jQuery will make the entire div clickable:
[jquery]
$(".myBox").click(function(){
window.location=$(this).find("a").attr("href");
return false;
});

 

 

 

 

 
by Janeth Kent Date: 13-02-2014 jquery resources tutorials tips plugins snippets webdev hits : 11316  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN END DEVELOPMENT.

 
 
 

Related Posts

How to watch deleted or private Youtube videos

Today we are going to talk about the technique which you permit to be able to recover videos from Youtube that was deleted, made private or simply blocked by Youtube…

How to ‘leave’ a WhatsApp group without actually leaving

If you want to leave a WhatsApp group but don't want the 'You left the group' message to be displayed, read this article. Some people love WhatsApp groups, and some people…

The 6 Essentials for Creating a Visually Appealing Web Design

Creating a website might seem like a simple thing. After all, what do you really need besides a good hosting provider and relevant content, right? Well, the reality is quite…

How to get notified when one of your WhatsApp contact is online

Privacy is one of the most important aspects among most users of the popular Facebook messaging application. So much so, that many settings have been included in WhatsApp itself to…

How to change font size and format in WhatsApp

Your WhatsApp messages can be much more original and fun by changing the font, size, or format. Here's how. WhatsApp is the leading messaging app for virtually everyone, with permission from…

WhatsApp: How to View Deleted Messages

Words are carried away by the wind, as long as they are not written on WhatsApp. Sending it was like getting a tattoo, something you'll always like, or yet it'll…

How to enable Chrome's new feature that blocks ads that consume your CPU, battery, and Internet connection

Google has announced that it will begin experimenting with a technology that they have been developing for months, in order to improve the battery consumption of our computers and the…

Protect yourself: know which apps have access to your location, microphone and camera

When you install an application on your smartphone, you decide what permissions you give it, but it's not always clear. We tell you how to know if those permissions are…

Can Easier Returns Mean Better Business?

Any eCommerce business owner knows that returns are a part of the packaged deal. At the end of the day, today’s consumer holds all of the power. They are informed,…

How to disable the camera, microphone and all sensors on your phone with a single touch in Android 10

With Android 10, Google has improved the privacy of its operating system with new options, but has also hidden an interesting option that deactivates all the sensors of the device…

Java 12, finally less verbose?

We all know Java for its characteristics thanks to which, despite more than 20 years have passed since the first version, it is still one of the most studied and…

Vanilla JavaScript equivalent commands to JQuery

JQuery is still a useful and pragmatic library, but chances are increasingly that you’re not dependent on using it in your projects to accomplish basic tasks like selecting elements, styling…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration