0

I don't want to repeat my code so I am trying to figure out how to work with a click event on multiple elements:

$(document).ready(function() {
    var realStateBtn = $('#real-estate-center').parent();
    var link = $('#real-estate-center > .linkwidth');
    realStateBtn.css('zIndex', 9999);
    realStateBtn.click(function() {
        console.log('TRIGGERED');
        window.location.href='http://realestatecenter.bankofamerica.com/';
    });

    link.click(function() {
        window.location.href="http://realestatecenter.bankofamerica.com/";
    });
});

as you see the vars realStateBtn and link take you to the same place/has the same function applied so what can I do in order to put the same code into one function?

I know I can do something like this:

$('.class1, class2').click(...)

but in this case I have this elements:

$('#real-estate-center').parent();

$('#real-estate-center > .linkwidth');

Suggestions?

3 Answers 3

1

You can use the .add() method to combine jQuery objects.

realStatebtn.add(link).click(function() {
    console.log('TRIGGERED');
    window.location.href='http://realestatecenter.bankofamerica.com/';
}
Sign up to request clarification or add additional context in comments.

Comments

0

It's exactly as you said: move the code into a single function:

function move() {
   window.location.href='http://realestatecenter.bankofamerica.com/';
}

realStateBtn.click(move);
link.click(move);

Here is a jsfiddle showing the concept: https://jsfiddle.net/b0ynfnmn/

Comments

0

You could add a common class and listen the click event on this class:

// Store the elements you want to an array
var elems = [];
elem.push(realStateBtn);
elem.push(link);
// You can add more elements ...

Now iterate the array and add the same class:

for(var elem in elems) {
   elems[elem].addClass('my-element');
}

Add the appropriate event listener (using event delegation in order to work):

// Add event listener using event delegation
$(document).on('click', '.my-element', function() {
   window.location.href="http://realestatecenter.bankofamerica.com/";
});

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.