Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.