0

I have the following code:

$('#picture-div').click(function(){
    $('#div-in-document').fadeToggle('slow', $func1);
});
$('#picture-div2').click(function(){
    $('#div-in-document2').fadeToggle('slow', $func2);
});

I'm trying to make this into one single click event, but can't seem to make it work. I've tried the following:

$('#picture-div ,#picture-div2').click(function(){
    if($(this) == '#picture-div')
        $('#div-in-document').fadeToggle('slow', $func);
    else
        $('#div-in-document2').fadeToggle('slow', $func2);
});

But that always go to the else, so my if-statement is invalid.

Thanks.

3 Answers 3

3

Change your markup using data-* attributes like:

<div class="picture-div" data-target="someId">...</div>
<div class="picture-div" data-target="someOtherId">...</div>

And your js will be just:

var yourFunctions = {
  someId : function(){...}.
  someOtherId : function(){...}
}

$('.picture-div').click(function(){
  var target = $(this).data('target');
  $('#' + target).fadeToggle('slow', yourFunctions[target]);
});

Maintainability is safe, hoorray.

Sign up to request clarification or add additional context in comments.

1 Comment

Looks like the person who was correct deleted his post(?). Anyway, I tried this, and it worked very well, thank you!
0

Try this instead and I hope it will work

$('#picture-div ,#picture-div2').click(function(){
    if($(this) == $('#picture-div'))
        $('#div-in-document').fadeToggle('slow', $func);
    else
        $('#div-in-document2').fadeToggle('slow', $func2);
});

I have not tested it but I am pretty sure that it will work

4 Comments

If I click one, both is displayed, so not working. The same happens with Zenith suggestion
Can you please paste the code for your div as well because according to me the above code should work
heres the fiddle: jsfiddle.net/Nilzone/cvHdQ (line 32-35 is the relevant code)
but I think this is the same as I have written above. Please let me know if there is some difference
0

Maybe something like this:

$('#picture-div ,#picture-div2').click(function(){
    if($(this).attr("id") == '#picture-div')
        $('#div-in-document').fadeToggle('slow', $func);
    else
        $('#div-in-document2').fadeToggle('slow', $func2);
});

Or you can make a kind of mapping:

var arr = [ { selector: "#picture-div", subselector: "#div-in-document", func: $func1},
            { selector: "#picture-div2", subselector: "#div-in-document2", func: $func2}]

and go through it for assigning handler:

for(int i = 0; i < arr.length; i++)
{
    $(arr[i].selector).click(function(){
      $(arr[i].subselector).fadeToggle('slow', arr[i].func);
   });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.