Reputation: 1051
I have three buttons on the page and I want to update the value of a variable based on each click event. I have done something like below but I think that is not the right approach I need something generic which follows the best practice but I don't know how. your help will be highly appreciated.
$('#digital_story_cover_image #imageset-fancybox').click(function() {
list = $('.cover-image');
});
$('#gallery_main_images #imageset-fancybox').click(function() {
list = $('.gallery-images');
});
$('#gallery_main_images #multi-imageset-fancybox').click(function() {
list = $('.gallery-images');
});
Thanks.
Upvotes: 0
Views: 93
Reputation: 21
This looks fine to me too, as @Lloyd Nicholson said: It defines certain outcomes and they are all specific to what is needed in your project.
However, you could refactor this and end up with only two on click events like so:
$('#digital_story_cover_image #imageset-fancybox').click(function() {
list = $('.cover-image');
});
$('#gallery_main_images #imageset-fancybox, #gallery_main_images #multi-imageset-fancybox').click(function() {
list = $('.gallery-images');
});
As you actually do the same thing in the last two events you have, you can use the same 'on click event' on multiple selectors using a comma between them.
*I think it would be good to have your code and more explanation on your issue, so we can provide better answers. I hope this is what you needed though.
Upvotes: 0
Reputation: 711
We can try avoiding multiple lines of code.
Just write event click event handler for all the selectors. like below
$('#digital_story_cover_image #imageset-fancybox, #gallery_main_images #imageset-fancybox, #gallery_main_images #multi-imageset-fancybox').click(function(e) {
list = $($(e).parent().attr('data-list-selector'));
});
and in html respective parents you can add attribute data-list-selector.
like
div with id digital_story_cover_image add attribute data-list-selector=".cover-image" likewise do it for the other parents as well.
Upvotes: 1
Reputation: 484
Like this to make recalling those accessors easier.
const digId = $('#digital_story_cover_image #imageset-fancybox');
digId.click(function() {
list = $('.cover-image');
});
const galId = = $('#gallery_main_images #imageset-fancybox');
galId.click(function() {
list = $('.gallery-images');
});
const galIdMulti = $('#gallery_main_images #multi-imageset-fancybox');
galIdMulti.click(function() {
list = $('.gallery-images');
});
Same could be done for all accessors seen here. e.g.
const galImg = $(‘.gallery-images’);
Upvotes: 0