ProPokerUK
ProPokerUK

Reputation: 21

Changing image src on button click

I have a holding page for a site Under Construction.

There is an image and a box with a button. on clicking the button I want the image to change.

There will be collections of images with the same name plus a subscript (eg: TG-img-01.jpg).
Idea is to increment the subscript.

Not used JavaScript for 15 years, so looking for examples of how it can be done.

cheers.

Upvotes: 1

Views: 16236

Answers (3)

andrewf
andrewf

Reputation: 375

Given the tag is javascript and not jQuery I would favour a solution that meets that requirement. In that case:

let counter = 0; // declared in global scope
document.querySelector('button').addEventListener('click', function() {
    	counter++; // increment this instead of rand int so it's 0,1,2 etc
    	buildimg = `TG-img-${counter}.jpg`;
    	document.querySelector('#imageID').setAttribute('src', buildimg);
      document.querySelector('div').innerHTML = buildimg;
    });
<button>Click me</button>
<img id="imageID" src=""/>
<div></div>

Upvotes: 3

Munkhdelger Tumenbayar
Munkhdelger Tumenbayar

Reputation: 1884

i just giving random number for your image increment. so this is just changing img source whenever you click button randomly generated number with your image name like TG-img-01.jpg if you dont understand this let me know glad to help you

$('button').click(function() {
  randint = Math.floor(Math.random() * 10) + 1;
  buildimg = 'TG-img-' + randint + '.jpg' 
  $('div > span').text('TG-img-' + randint);
  $('div > img').attr('src', buildimg);
  console.log(buildimg);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <span>imagine its like picture with TG-img-01.jpg</span>
  <img src='https://www.askideas.com/wp-content/uploads/2017/06/Free-Online-Photos1.jpg'>
</div>
<button>
change
</button>

Upvotes: 0

Venkat Raj
Venkat Raj

Reputation: 219

Try this below sample code.

<script>
 function pictureChange()
  {
   document.getElementById("theImage").src="img02.png";
  }
</script>

<body>
 <img id="theImage" src="img01.png">
 <p><input type="button" id="theButton" value="click me!" 
    onclick="pictureChange()"></p>
</body>

Upvotes: 2

Related Questions