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.
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.
Share Improve this question edited Nov 2, 2017 at 12:19 ShahiM 3,2681 gold badge35 silver badges62 bronze badges asked Nov 2, 2017 at 3:30 ProPokerUKProPokerUK 211 gold badge1 silver badge6 bronze badges 2- What have you tried? Post some code... Even if it's bad... It's easy to get answers here, but it's impossible to help you as your post is stated – wahwahwah Commented Nov 2, 2017 at 4:47
- improved formatting and grammar – ShahiM Commented Nov 2, 2017 at 12:19
3 Answers
Reset to default 3Given 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>
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>
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./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./wp-content/uploads/2017/06/Free-Online-Photos1.jpg'>
</div>
<button>
change
</button>