jQuery multiple click handling

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


jQuery multiple click handling



I have the code below working to handle clicking a link from a list, showing a screen, and then hiding it when the .back button is pressed.


link


list


.back



Is there a cleaner way to handle the click function for any x number of list items?


x


list


$(".container").on("click", ".dog-btn", function() {
$(".screen1").css("display","flex")
});
$(".container").on("click", "#back", function() {
$(".screen1").css("display","none")
});
$(".container").on("click", ".cat-btn", function() {
$(".screen2").css("display","flex")
});
$(".container").on("click", "#back", function() {
$(".screen2").css("display","none")
});
$(".container").on("click", ".bird-btn", function() {
$(".screen3").css("display","flex")
});
$(".container").on("click", "#back", function() {
$(".screen3").css("display","none")
});





From what I see, you just need one handler for #back, which to hide all 3 screens.
– choz
8 mins ago


#back





Can you post your html too ?
– David Jaw Hpan
6 mins ago




1 Answer
1



You can use html5 data attributes to pass screen classes.



HTML CODE


<div class="container">
<button class="flex" data-screen="screen1"> DOG</button>
<a href="void(0)" data-screen="screen1" class="back">Back </a>
</div>



JavaScript Code


//Flex Handler
$(".container").on("click", ".flex", function() {
$("."+$(this).data("screen")).css("display","flex")
});
//Back Button Handler
$(".container").on("click", ".back", function() {
$("."+$(this).data("screen")).css("display","none")
});



Hope it helps.





Yep, data-* surely helps in this OP case.
– choz
1 min ago


data-*






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Makefile test if variable is not empty

Will Oldham

Visual Studio Code: How to configure includePath for better IntelliSense results