Jump to content

new to jQuery, tips on what to start with


petewall

Recommended Posts

Hi, i've recently read a bit about jQuery, and started to write some code today, this is what i came up with so far:

$("#mydiv").click(function() {

if($(".myclass").is(":hidden")) {

$(".myclass").slideDown("slow");

}

else {

$(".myclass").slideUp("slow");

}

});

superbasic stuff that slides down a <div> on click.

well, i'd love some tips on what to do next, something not to advanced and maybe even some pointers on what to look at to get the script done.

The first thing that you should learn is about selectors. Your already using them in your example, but very inefficiently. Every time you use $('someselector') jQuery searches the DOM for that element, therefore, if your going to use the same element more than once, save it locally.

 

$("#mydiv").click(function() {
  $myclass = $(".myclass");
  if ($myclass.is(":hidden")) {
    $myclass.slideDown("slow");
  } else {
    $myclass.slideUp("slow");
  }
});

alright, does it work the same if i declare it outside the function?

like

 

$myclass = $(".myclass");

and then

 

$("#mydiv").click(function() {

if ($myclass.is(":hidden")) {

$myclass.slideDown("slow"); 

} else { 

  $myclass.slideUp("slow");

}

});

or does it have to be within the function?

Yeah that's fine. Unlike with PHP where you have to declare variables inside a function as global, JS automatically has scope of global variables. Adding to what thorpe said, you can also improve the performance of a selector by adding the element tag ("div.myclass" instead of ".myclass" for example), as it reduces the number of elements to check.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.