Reputation:
currently I am a beginner in JavaScript. I would like to make my website can change a picture everytime I click a button.
This is my HTML file:
<div id="images">
<img src="img/80673284_74c3361ed19c018192c338d338d27d67.jpg" id="previewimage">
</div>
<button onclick="changepic()" id="buttonback" class="btn btn-primary">Back</button>
After I click the button, the changepic
function will be executed. And this is my Javascript code :
function changepic(source){
document.getElementById('previewimage').src = source;
}
And I take the "source" parameter as a string variable which is a link.
My plan is to call this function for every elements in my array which I called "link". But Isn't that mean I need to make my variable link=[]
as a global variable? I thought, doing javascript, we need to avoid global variable as much as possible. To create the link every time I press the button will not be possible since it is not efficient.
Any idea?
Upvotes: 0
Views: 142
Reputation: 4584
How about this ! It can avoid your link from global variable ....
<script type="text/javascript">
function link() {
return [
"link1",
"link2",
"link3"
];
}
function changepic(){
var lk = link();
//implement code
//document.getElementById('previewimage').src = source;
}
</script>
Upvotes: 0
Reputation: 16675
"I thought, doing javascript, we need to avoid global variable as much as possible" - It's true that global variables are to be used only when necessary, but you should not avoid them altogether.
In your case, the alternative for not using a global variable is passing an argument to the function, with the current image name, or index, or querying the current image used using the element's attributes, which would make the code a bit more messy and over complicated, so there's nothing wrong with using a global parameter with your code.
As you suggested, create a links
array and increment its index on every click.
Here's an example.
var currentImage = 0;
var links = [
"http://www.gstatic.com/webp/gallery/1.jpg",
"http://www.gstatic.com/webp/gallery/2.jpg",
"http://www.gstatic.com/webp/gallery/3.jpg"
];
function changepic() {
// Increment the value
currentImage++;
// Reset the counter if all images were used
if (currentImage >= links.length)
currentImage = 0;
document.getElementById('previewimage').src = links[currentImage];
}
<div id="images">
<img src="http://www.gstatic.com/webp/gallery/4.jpg" id="previewimage" width="200">
</div>
<button onclick="changepic();" id="buttonback" class="btn btn-primary">Back</button>
Upvotes: 2