Reputation: 123
I have two javascript functions and I want them both to run when I press a button. I have tried different things but only one would work and not the other. I ran the function startTimer onclick on the button but don't know how to run the first one where the text is displayed.
JS:
$(function () {
count = 0;
wordsArray = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5"];
setInterval(function () {
count++;
$(".questions1").fadeOut(400, function () {
$(this).text(wordsArray[count % wordsArray.length]).fadeIn(400);
});
}, 8000);
});
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
document.getElementById("img").src = images[x];
}
function startTimer() {
setInterval(displayNextImage, 8000);
}
var images = [], x = -1;
images[0] = "img/question-2.png";
images[1] = "img/question-3.png";
images[2] = "img/question-4.png";
images[3] = "img/question-5.png";
images[4] = "img/question-6.png";
HTML
<img id="img" src="img/question-1.png" alt="">
<h1 class="questions1">Text 1</h1>
<button id="begin" onclick = "startTimer()">Begin</button>
Upvotes: 0
Views: 128
Reputation: 427
You can just call the two functions you want from within the click handler, like this:
function onClick(){
startTimer();
otherFunction();
}
You may want to think about function names some more, but that's the general structure.
Upvotes: 0
Reputation: 169
You need a function to manage what exactly you want to happen onclick. I would create a wrapper function to call the two functions.
function onClickWrapper(){
//Do onclick stuff
startTimer();
otherFunction();
}
Then just modify your HTML:
<img id="img" src="img/question-1.png" alt="">
<h1 class="questions1">Text 1</h1>
<button id="begin" onclick = "onClickWrapper()">Begin</button>
Upvotes: 1
Reputation: 503
You should trigger this button via jQuery rather than using an onclick
attribute in HTML.
For example you could do this:
$('#begin').on('click', function(){
firstFunction();
secondFunction();
});
And you would have both functions executed when you click the button.
Upvotes: 4