jonleech
jonleech

Reputation: 461

Fade in and out depending on div id

I have a jquery code to distinct between two divs

$("#addresslink").click(function() {
    $("#main").find("div").each(function(n,i){
        var id = this.id;
        if(id == "addressdiv")
        {
            $('#' + id).fadeIn(300);
        }
        else
        {
            $('#' + id).fadeOut(250);
        }
    });

});


$("#storylink").click(function() {
    $("#main").find("div").each(function(n,i){
        var id = this.id;
        if(id == "storydiv")
        {
            $('#' + id).fadeIn(300);
        }
        else
        {
            $('#' + id).fadeOut(250);
        }    
    });

});

is there a better way to tie a to a div rather than hardcoding each to a then showing and hiding the other divs?

P.S: I have done the code just asking whether could i optimize this?

Upvotes: 2

Views: 2100

Answers (2)

insomiac
insomiac

Reputation: 5664

One way to optimize without changing anything is move the common code to function:

$("#addresslink").click(function() {
   fadeDiv('addressdiv');
});

$("#storylink").click(function() {
    fadeDiv('storydiv');     
});

function fadeDiv(divName) {
  $("#main").find("div").each(function(n,i){
            var id = this.id;
            if(id == divName)
            {
                $('#' + id).fadeIn(300);
            }
            else
            {
                $('#' + id).fadeOut(250);
            }    
        });
}

OR

you can also do this :

$("#addresslink,#storylink").click(function() {
    fadeDiv(($(this).attr('id')=='addresslink')?'addressdiv':'storydiv');
});

function fadeDiv(divName) {
  $("#main").find("div").each(function(n,i){
            var id = this.id,
$id = $('#' + id);
            (id == divName)? $id.fadeIn(300):$id.fadeOut(250);
        });
}​

Upvotes: 2

Snake Eyes
Snake Eyes

Reputation: 16764

Do you mean :

$("#addresslink, #storylink").click(function() {
    $("#main").find("div").each(function(n,i){
        var id = this.id;
        if(id == "addressdiv")
        {
            $('#' + id).fadeIn(300);
        }
        else
        {
            $('#' + id).fadeOut(250);
        }
    });
});

Upvotes: 2

Related Questions