1

I need to have multiple .click() functions populated on page load, based on how many image records are stored within a mysql database.

so far i have a page that will nicely switch between photos with a <ul> of image buttons

but i have to hand write the jquery that deals with it.

is there a way that i can populate a .js file with the correct amount of .click() functions based on the amount of records on in the data base.

3 Answers 3

3

In addition to Alex's answer, if you want to set the click event of elements that don't exist yet or haven't been added to the page, you could do:

$(body).on('click','a.record',function(){
    //any existing or future a element with class record will have this click function
});
Sign up to request clarification or add additional context in comments.

Comments

1

Instead of adding a separate onclick handler to each element, you should use event delegation and attach a single event handler to some container. Said event handles would catch all the onclick events , as the bubble up through DOM.

Comments

-1

You don't need to write a click() for each unique element.

Instead, you could select a bunch of elements with a selector, such as $('a.record') and then chain click() to that...

$('a.record').click(function() {
   // Any `a` element with a class of `record` was clicked.
});

The disadvantage of doing it this way is you add a bunch of event listeners and it won't be triggered for future elements.

As others have mentioned, event delegation using on() (if using a newer jQuery) or delegate() (if using an older) is the best, as it only attaches one event listener and will work with future elements added after the event is attached.

$(document).on('click', 'a.record', function() {
   // Any `a` element with a class of `record` was clicked, now or in the future.
});

I've used document here, but you should use the nearest ancestor which won't change, which may be the ul element you have described.

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.