Morris Pinedo Michelsen Morris Pinedo Michelsen - 1 year ago 96
Javascript Question

How to show multiple images based on click events on multiple buttons with Jquery

I want to have multiple buttons that trigger a function that changes the src on an img tag.
Each button make an specific image show inside that one img tag. It's a site where I want to show different floor plans available for an apartment, so the buttons says "Type 1", "Type 2", "Type 3", "Type 4", etc.
There is not an specific amount of types for each project.
I would like to make the function work, no matter how many options there are.

I have this right now, but don't know how to continue

<section id="floor-plans">
<div class="wrapper">
<div class="img-links">
<input type="button" onclick="changeImg()" value="Tipo 1">
<input type="button" onclick="changeImg()" value="Tipo 2">
<input type="button" onclick="changeImg()" value="Tipo 3">
<input type="button" onclick="changeImg()" value="Tipo 4">
<input type="button" onclick="changeImg()" value="Tipo 5">
<div class="featured-img">
<img src="images/planos/001.jpg" alt="">

I could manage the "X" amount of options with

var options = $('img-links input').lenght();

but cant figure out how to continue.

This image represents more clearly what I want to achieve

Thanks in advance
view image

Answer Source

You want to use event delegation. You add a click event to the parent (img-links) which processes clicks bubbling up from the buttons.

Also, you would be better off separating the button value from the img src.

$('.img-links').on('click', 'input', function(){
    var src = $(this).attr('data-src');
    $('.featured-img img').attr('src', src);

Remove the onclick attribute:

  <div class="img-links">
    <input type="button" value="Tipo 1" data-src="/image01.jpg" />
    <input type="button" value="Tipo 2" data-src="/image02.jpg" />
    <input type="button" value="Tipo 3" data-src="/image03.jpg" />
    <input type="button" value="Tipo 4" data-src="/image04.jpg" />
    <input type="button" value="Tipo 5" data-src="/image05.jpg" />

The code needs to be executed after .img-links exists in the DOM, preferably by adding in a $(document).ready(function(){ ... });, but it can executed before the input buttons are added so you could dynamically add more after page load and it will still work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download