Why is Jquery .click() firing multiple functions? - javascript

I've been making a game to practice programming, and I am having trouble using the Jquery .click() function. I have two buttons in my code, the start button and the attack button. When I click the start button, the .click() function fires the code for the other button as well, which causes my main menu to freeze up and not draw the game screen. I've used separate id's for the buttons, but they both seem to recognize the click on the start button. I can't get it to work in JSFiddle, but all the code is there. Can someone please tell me how to use multiple buttons?
//start button
$('#startButton').click(function() {
stage.state = "battle";
stage.update();
})
//attack button
$('#attack').click(firstTurn());
//attack button code
function firstTurn() {
console.log("firstTurn Fired");
if(p1.speed > opp.speed){
turn = 1;
} else{
turn = 0;
}
battle();
};
function battle(){
var battling = 1;
while(battling == 1) {
if(turn == 0) {
p1.health = p1.health-opp.attack;
$("#textBox").append('<p>'+opp.name+' hit you for '+ opp.attack+' points.</p><br/>');
draw();
sleep(1000);
console.log("attacked");
} else{
opp.health = opp.health-p1.attack;
$('#textBox').append('<p> You hit '+opp.name+' for '+p1.attack+' points.</p><br/>');
draw();
sleep(1000);
}
}
};
https://jsfiddle.net/memersond/m3gvv8y6/

$('#attack').click(firstTurn());
Should be:
$('#attack').click(firstTurn);
You want to pass the function as a reference, not have it executed immediately.

$('#attack').click(firstTurn());
This causes firstTurn() to be called when the listener is initiated, use one of the alternatives:
$('#attack').click(firstTurn );
$('#attack').click(function() {
firstTurn()
});

Related

Cant understand why my onclick does not work

I am currently studying Javascript and came across a problem while practising setInterval() and `clearInterval().
I am writing a timer that will stop as soon as I press on a button. I have a variable in which I start the interval, a function that executes the timer code and writes the current number the timer is on into a div in HTML.
Then I have a getElementById call that writes an onclick into a button with an id of theButton which contains a clearInterval.
The problem is, if I just write the clearInterval right in the end of the code, without an onclick, it works. But as soon as I write it inside an onclick, it doesn't work without even showing a error.
I have tried searching on the internet and the only answer I got was to use a var instead of a let for the variable with the interval, but that didn't work.
var timerVariable = setInterval(theTimer, 1000);
let count = 11;
function theTimer() {
if (count != 0) {
count--;
document.querySelector("div").innerHTML += count;
console.log("its working");
}
}
document.getElementById("theButton").onclick = 'clearInterval(timerVariable)';
The main reason it doesn't work is because you should assign a function reference to onclick, not a string. Your code should look something like this:
document.getElementById("theButton").onclick = function() {
clearInterval(timerVariable);
});
However, taking this a step further, the onclick is no longer considered good practice. A better solution is to attach your events using addEventListener(), like this:
document.querySelector('#theButton').addEventListener('click', () => {
clearInterval(timerVariable);
});
Here's a full working version with the above correction applied. Note that I added an else case to also clear the interval when the count reaches 0. Without this the interval will run infinitely without any purpose.
var timerVariable = setInterval(theTimer, 1000);
let count = 11;
function theTimer() {
if (count != 0) {
count--;
document.querySelector("div").innerHTML += count;
console.log("its working");
} else {
clearInterval(timerVariable);
}
}
document.querySelector("#theButton").addEventListener('click', () => {
clearInterval(timerVariable);
});
<button type="button" id="theButton">Stop</button>
<div></div>

HTML buttons will only work only on webpage re/-load

EDIT : Thanks to everyone who tried to help me. I appreciate the tips guys.
I changed my window.onloadand inserted the two event listeners inside of it.
After that I took the idea of #Ito Pizarro , and implemented it in my own way.
The result looks like this :
function openDoor() {
var x_1 = document.getElementById('img1');
var x_2 = document.getElementById('img2');
is_visible = (x_1.style.visibility == "hidden");
if (is_visible) {
x_1.style.visibility = "visible";
}
else {
x_2.style.visibility = "hidden";
}}
And I also did the same for my closeDoor() function.
END OF EDIT
I create a HTML page, with two buttons. Every button has its purpose when it's being clicked. The first one will show an image of an opened door. The second button will show an image of a close door. When the page is loaded no image is being shown. They appear only if their button is clicked.
Tried to created a nested if-statement with the a global bool that will make it run infinitely.
Also tried a for & while loop.
But I am new to programming and I struggle a bit.
window.onload = function () {
document.getElementById('OpenDoor').addEventListener("click", function () { openDoor() })
}
window.onload = function () {
document.getElementById('CloseDoor').addEventListener("click", function () { closeDoor() })
}
function openDoor(){
document.getElementById('img1').style.visibility = "visible";
}
function closeDoor(){
document.getElementById('img2').style.visibility = "visible";
}
In the code exist two problems :
I load the page and click the "close door" button and the closed door image appears. If I decide to open the door again by pressing the "open door" button, it wont do it.
I load the page and click the "open door" button first. The open door image appears and the if I click on the "close door" button and the image also appears, but I cant repeat the process by re-clicking the "open door" to reopen it.
You are assining a function on the onload event twice. By doing this the first delaration will never be triggered.
It should be more something like :
window.onload = function () {
document.getElementById('OpenDoor').addEventListener("click", function () { openDoor() })
document.getElementById('CloseDoor').addEventListener("click", function () { closeDoor() })
}
Don't forget to validate the answer if you have what you were looking for
EDIT: In addition to lucien-dulac's point about window.onload…
It looks like your two event handlers do a single thing to either of two separate elements.
openDoor() will only ever make #img1 visible.
closeDoor() will only ever make #img2 visible.
If you want subsequent clicks on #OpenDoor or #CloseDoor to change the visibility style of their respective target elements — #OpenDoor controls #img1, #CloseDoor controls #img2 — you would need to write a toggle into openDoor() and closeDoor().
Something like…
function openDoor(){
var el = document.getElementById('img1'),
is_visible = ( el.style.visibility === "visible" );
if ( is_visible ) {
el.style.visibility = "hidden";
} else {
el.style.visibility = "visible";
}
}

How can one <img> tag be used to execute 2 different js functions?

How can I set up one image, that when clicked changes to another image and then when clicked again reverts back to the original image while still carrying out functions independently. In my example I want a Play button that when pressed turns to a pause button. However I need to have both play and pause functionalities when the correct button is pressed. These work on do different buttons but I would like the one button to have all the functionality. I have tried a few things but everytime, one of the play/pause functions are not letting the other work.
$('#startSlider').click(function (){
if (document.getElementById("startSlider").src = "Play.png"){
document.getElementById("startSlider").src = "Pause.png";
scrollSlider();
}
else if (document.getElementById("startSlider").src != "Play.png"){
clearTimeout(tmOt);
document.getElementById("startSlider").src = "Play.png";
}
});
<img src="Play.png" id="startSlider"/>
problem is in your if block,
you are using = not ==
if (document.getElementById("startSlider").src = "Play.png"){// you are assigning here not comparing
you are assigning play.png every times when the click calls on the image.
you are using jquery then why are you not using this to make it more simple.
$('#startSlider').click(function (){
if (this.src == "play.png"){
this.src = "pause.png";
}else{
this.src = "play.png";
}
});
check this fiddle
I like using classes in these situations as it makes the code a little easier to follow:
$('#startSlider').click(function (){
$(this).toggleClass('pause')
if ( $(this).hasClass('pause') ) {
// Button is paused change to play
$(this).attr('src', 'Play.png')
// Pause function goes here
} else {
// Button is play change to pause
$(this).attr('src', 'Pause.png')
//play function goes here
}
})
You can do this with a little state machine. You keep the states inside an object, and handle the next state in the event listener of the button:
var states = {
_next: 'play',
next: function() {
return this[this._next]()
},
play: function() {
img.src = 'pause.jpg'
button.textContent = 'Pause'
this._next = 'pause'
},
pause: function() {
img.src = 'play.jpg'
button.textContent = 'Play'
this._next = 'play'
}
}
button.addEventListener('click', states.next.bind(states))
This is more of a general answer to your problem, that you'd have to adapt to your code.
DEMO: http://jsbin.com/moxoca/1/edit *
* The images might take a second to load.

JQuery Mobile Slider Not ReEnabling

So I think I am doing everything correct with my jquery mobile slider, but the control is not being re-enabled. I've made a pretty decent jsFiddle with it, in hopes someone will spot the error quickly.
On the fiddle you will see the jQuery moblie control. If you click and move the slider position the event will fire that the control value changed. If you end up changing the value more than 5 times within 20 seconds the control will lock up. You can think of this as being a cooldown period. Well after the control cools down it should be re-enabled for more mashing.
Problem is, the control never comes back from being disabled!
http://jsfiddle.net/Narq6/
Sample Javascript:
var sent = 0;
var disabled = false;
$('#slider-fill').on( 'slidestop', function()
{
send();
writeConsole(sent);
})
function send()
{
setTimeout(decrease, 4000);
sent +=1;
if(sent > 5)
{
$('#slider-fill').prop('disabled', 'disabled');
disabled = true;
}
}
function decrease()
{
if(sent > 0)
sent -= 1;
writeConsole('decrease');
writeConsole(sent);
if(sent === 0)
{
//CODE TO DISABLE HERE!!!
//LOOK HERE THIS IS WHERE I REMOVE THE DISABLE!!!
writeConsole('no longer disabled!');
$('#slider-fill').prop('disabled', '');
///YOU LOOKED TOO FAR GO BACK A LITTLE BIT :D
}
}
function writeConsole(message)
{
var miniconsole = $('#miniConsole');
var contents = miniconsole.html();
miniconsole.html(contents + message + '<br/>' );
miniconsole.scrollTop(10000);
}
You were using incorrect enable/disable syntax.
This one is a coorect syntax:
$('#slider-fill').slider('disable');
and
$('#slider-fill').slider('enable');
Here's am working example made from your jsFiddle: http://jsfiddle.net/Gajotres/djDDr/

Toggling on the first click

I've tried two different methods of toggling the play/pause button on my player, neither of which work on the first click, for some reason.
This one, supposedly checks the status of the audio to see if it's paused or ended:
function togglePlayPause() {
var audioPlayer = document.getElementsByTagName('audio')[0];
var playpause = document.getElementById("playpause");
if (audioPlayer.paused || audioPlayer.ended) {
playpause.title = "pause";
playpause.innerHTML = "pause";
}
else {
playpause.title = "play";
playpause.innerHTML = "play";
}
}
Or I've tried this one, which just toggles via the onClick toggle(this):
function toggle(obj) {
if (obj.className== 'playButton') {
obj.className = 'pauseButton';
obj.title = "PAUSE";
obj.innerHTML = "PAUSE";
} else {
obj.className = 'playButton';
obj.title = "PLAY";
obj.innerHTML = "PLAY";
}
}
Neither toggle the first time the button is clicked, although the first method does change from the default inner "PLAY" to "play", so I guess that's something:
<div title="play" class="playButton" id="playpause">PLAY</div>
In both methods, subsequent clicks work fine. Any idea why this is happening? Could it have something to do with the way the audioPlayer variable is called? The array starts from 0. (I'm clutching at straws.)
Many thanks as usual!
I would go without creating functions, I would check if the link is clicked then proceed to the events that would be fired.
so something like $("#start").click(function(){}); in can be tried.
First, have the jQuery library included in your HTML header.
Then create a new javascript file, included it as well (usually this is put after the jQuery included)
In your new javascript file write the following
$(document).ready(function() {
$("#start, #stop, #play, #pause").click(function() { //you can have more or less selectors (selectors are the ones with #)
//Your code goes here
});
});
Here is a fiddle for that solution. http://jsfiddle.net/JRRm2/1/ (tidier text: http://jsfiddle.net/JRRm2/2/)

Categories

Resources