M de Froe M de Froe - 1 year ago 59
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() {

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
.Img-Toggle2 show .slideDown2 on click

without having to create a new code every time?

Answer Source

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

    var link = $(this).data("link");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download