jQuery - Save selection as variable




If yo uhave to make selection of a page element several timem you need to call the jQuery function again. This cab slow dowsn the program and may result in poorer browsing experience. Take a look at the following example


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
  
    $("p.aboutme").html("<p> You are the most stupid person I have ever seen</p>");
    $("p.aboutme").fadeOut(1500); 
    $("p.aboutme").fadeIn(1500); 
    
 });
});
</script>
</head>

<body>
<h2>Reference Designer jQuery Tutorial</h2>
<p class="aboutme"> I am the greatest person in the world </p>

<button>Click me to confirm this</button>
</body>
</html>


You may like to try this example online to see it in action - here.

This code selects the element with class aboutme. It then selects the element again and fades it in so it becomes invisible in 1500 ms. It selects the element a third time and makes it visible again in 1.5 seconds using fade out. Each of those selections runs the jQuery function. This may slow it down. All you need to do is select it just once. You can assign the selection in a variable as is done in the following.


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
     var $about = $("p.aboutme"); 
     $about.html("<p> You are the most stupid person I have ever seen</p>");
    $about.fadeOut(1500); 
    $about.fadeIn(1500);
    
 });
});
</script>
</head>

<body>
<h2>Reference Designer jQuery Tutorial</h2>
<p class="aboutme"> I am the greatest person in the world </p>

<button>Click me to confirm this</button>
</body>
</html>




Try this example online - here. The effects are same, but you save the coding time and speed up the browsing experience.