M de Froe M de Froe - 5 months ago 15
HTML Question

Repeat a javascript code for different classes without repeating the code

I have this code were you can click on an img to slide down a class.
Only i want to repeat this process for multiple cases, but the only way I know to do this is to repeat the javascript with different names.

Like this:

$( window ).load(function() {
$('.Img-Toggle').click(function(e){
$('.slideDown').slideToggle();
});
$('.Img-Toggle2').click(function(e){
$('.slideDown2').slideToggle();
});
$('.Img-Toggle3').click(function(e){
$('.slideDown3').slideToggle();
});
});


I also tried something like this:

$('.Img-Toggle .Img-Toggle2 .Img-Toggle3').click(function(e){
$('.slideDown .slideDown2 .slideDown3').slideToggle();
});


but that showed all classes when clicking any of the images (of course)

How can I make
.Img-Toggle show .slideDown on click
and
.Img-Toggle2 show .slideDown2 on click
etc...

without having to create a new code every time?

Answer

Use a common class for the image toggles, and link the related elements using data-* attributes

<img class="img-toggle" data-link=".slideDown" src="...">
<img class="img-toggle" data-link=".slideDown2" src="...">

and write your code once

$('.img-toggle').click(function(e){
    var link = $(this).data("link");
    $(link).slideToggle();
});
Comments