1

I have a function that will run if any one of the multiple items on the page is clicked. The function works, I just want to know is there a better way of listing this using || or something similar.

This is what I have so far:

Init: function () {

        $('#indian-marker a').click(Operations.ShowIndia);
        $('#map-2 a').click(Operations.ShowIndia);
        $('#details-marker a').click(Operations.ShowIndia);

    },

    ShowIndia: function () {

        $('#map').css('background-image', 'url("../img/map-background-india.jpg")');
        $('#map-return').show();
        $('#india-box-link').toggle();
        $('#global-box-link').toggle(); 

        return false;

    }
1

2 Answers 2

4

, shoud work

Init: function () {

    $('#indian-marker a, #map-2 a, #details-marker a').click(Operations.ShowIndia);


},

ShowIndia: function () {

    $('#map').css('background-image', 'url("../img/map-background-india.jpg")');
    $('#map-return').show();
    $('#india-box-link').toggle();
    $('#global-box-link').toggle(); 

    return false;

}

You can review this examples from the documentation

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

2 Comments

so easy, really thought it would be the double pipes ||, thanks for clearing this up for me!
the syntax is the same as CSS, so everything working in CSS should work in jQuery selectors.
4

You can combine the selectors:

$('#indian-marker, #map2, #details-marker').find('a').click(Operations.ShowIndia);

I've moved the a part out of the selector into its own call to avoid it being repeated over and over.

Also, do be careful with that callback. Just because you've referred to it as Operations.ShowIndia doesn't mean that this === Operations when it's actually called. It would be safer to write:

... .click(function() {
    this.ShowIndia();
});

It doesn't matter in this particular function, but if you end up with other functions that rely on this it'll save confusion later.

1 Comment

The selector in this answer if more efficient than the accepted answer. It also points out the scoping issue inside the ShowIndia function. +1

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.