Button auto-clicks once on load, then can't be clicked - javascript

I'm trying to have a button click cause a variable to increment by one, then update a page counter showing the variable. For some reason, upon page load, the button will apparently click once, and any actual clicks do nothing.
I've tried $("#click").click(click(1)); and putting onClick="click(1)" on the actual HTML of the button, but both seem to output the same result.
Here's the relevant HTML:
<div class="column_middle">
<div style="font-size:115%;display:inline;">Money: <span id="money">0</span></div>
<button id="click" class="mainbutton" style="margin:10px;margin-right:5px;" title="">Click</button>
And the relevant javascript:
// Activated on DOM load
function onLoad( jQuery ) {
// Set up button functions
$("#click").click(click(1));
}
function click(amount) { // Player clicking
money += amount; // Add the amount of clicks to the total money
html_money.text(money); // Update page money value
console.log("Clicked "+amount+" times.");
}
// Variable declaration
var money = 0; // Total money
var stock = 0; // Total stock
var html_money = $("#money"); // Money variable on the actual page
var html_stock = $("#stock"); // Stock variable on the actual page

At least this line will not work: $("#click").click(click(1)); because on the click event, you will "execute" the returned value of the click function (void), not the function itself.
Try this:
<div class="column_middle">
<div style="font-size:115%;display:inline;">Money: <span id="money">0</span></div>
<button id="incrementButton" class="mainbutton" style="margin:10px;margin-right:5px;" title="">Click</button>
</div>
JS:
$(document).ready(function () {
var increment = function (amount) {
$('#money').text(
parseInt($('#money').text(), 10) + amount
);
}
$('#incrementButton').click(function () {
increment(1);
});
increment(1);
});
I also created a fiddle: http://jsfiddle.net/cP6Lq/

change your code to:
function incrementMoney(amount) { // Player clicking
$("#money").html( parseInt($("#money").html()) + amount);
}
$(document).ready(function () {
$("#click").click(function(){
incrementMoney(1));
});
}
it is very important to avoid using qualified names specially if you have element ids named just like functions..

Related

Show each div total amount in one div with every new action in jquery

Javascript Code:
$(document).on('click', '#google_analytics', function() {
if ($("#google_analytics").prop('checked') == true) {
var google_analytics_cost = $('#google_analytics_cost').val();
$('.total-amount12').text(google_analytics_cost);
} else {
$('.total-amount12').text('0');
}
});
$(document).on('click', '#mailing_list', function() {
if ($("#mailing_list").prop('checked') == true) {
var mailing_cost = $('#mailing_list_cost').val();
$('.total-amount13').text(mailing_cost);
} else {
$('.total-amount13').text('0');
}
});
I just want to add both actions total in one div. Which is named total-amt <div class="total-amt">0</div> In this div, whenever i click any action the total should show total-amt div and then, if i click on other action then its total amount too added with the previous amount.
Try this, when you click on any action it will take the previous value from that div, convert it into integer (parseInt) then it will add newValue in it. Finally, It will put the new sum into that div again.
Edit-1
You need to remove the $ string from the div. Try this working snippet.
//Action performed and Add the sum to that div
$('a').click(function(){
//New value that is going to add into div
var newValueToAdd = 10;
//Replace the HTML with final summation
$('.total-amt')
.html("$" +
(parseInt($('.total-amt').html().replace('$', '')) +
newValueToAdd));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="total-amt">$0</div>
Add

Event listener not working consistently Javascript

I have a web based quiz that loads a new question, with 4 choices and their respective radio buttons next to them. The problem is I have an event listener on the "next" button that triggers a new question and choices be loaded, except that the questions do not load. I believe it is because the step counter I have resets each time. Also something weird is that I have it output to console when the event listener fires, and sometimes when I press next it doesn't fire, and other times it does. I can't find a pattern.
I have included the relevant code with a link to JSFiddle if you want to see all of it. Thank you in advance. http://jsfiddle.net/d0u6cz7o/
function Quiz() {
this.step = 0;
this.questionSwap = function () {
document.getElementById('question').innerHTML = allQuestions[this.step].question;
document.getElementById('answer0').innerHTML = allQuestions[this.step].choices[0];
document.getElementById('answer1').innerHTML = allQuestions[this.step].choices[1];
document.getElementById('answer2').innerHTML = allQuestions[this.step].choices[2];
document.getElementById('answer3').innerHTML = allQuestions[this.step].choices[3];
};
var quiz = new Quiz();
quiz.questionSwap();
window.addEventListener('load', function() {
document.getElementById("next").addEventListener("click", function () {
console.log("Here");
quiz.questionSwap();
quiz.step++;
console.log("current question is " + quiz.step);
})
});
Change the submit into a button, remove the listener & change the order of the rotation:
<input id="next" type="button" value="Next!">
document.getElementById("next").addEventListener("click", function ()
{
quiz.step++;
quiz.questionSwap();
console.log("current question is " + quiz.step);
})
http://jsfiddle.net/d0u6cz7o/4/

Jquery .val() change the variable value by pressing the button

I want to pass the value of the limit in Jquery at the touch of a button. I almost found a solution, but can not quite understand. How to set the value to "limit:" the default and change it by pressing the button.
HTML
<button id="pagelimit default">1</button>
<button id="pagelimit">2</button>
<button id="pagelimit">3</button>
</div>
JS
function displayVals() {
var pagelim = $( "#pagelimit" ).val();
};
$('#product-grid').mixItUp({
pagination: {
limit: $pagelim // insert button value
}
});
Please help me solve this problem.
ID of an element must be unique... It looks like you want to update the limit option with the clicked button's text so
<button class="pagelimit default">1</button>
<button class="pagelimit">2</button>
<button class="pagelimit">3</button>
then
//this method is not used in the below code as we don't know which button was clicked here... if you share how the `displayVals` method is called then we can try to make this work
function displayVals() {
var pagelim = $("#pagelimit").val();
};
jQuery(function ($) {
$('.pagelimit').click(function () {
//update the limit option
$('#product-grid').mixItUp('setOptions', {
limit: +$(this).text()
});
});
//initialize the plugin
$('#product-grid').mixItUp({
pagination: {
limit: 1
}
});
})

Changing what function to call depending on which button is pressed

Okay So I what to have 3 buttons
<div id="button1" onclick="choose1()">Button1</div>
<div id="button2" onclick="choose2()">Button2</div>
<div id="button3" onclick="choose3()">Button3</div>
And a start button
<div id="startButton" onclick="noFunction()">Start</div>
I want to make it so that pressing on of the 3 option buttons it changes what function will be called from the start button and the background image of the start button should change.
Is there a way to do this with just javascript or do I need jquery?
It also doesn't seem possible to use onclick on div tags, jquery to do that aswell?
jsFiddle
You can use onclick on <div> tags. But you shouldn't use onclick on any tags. Don't confuse your HTML layout and display with your JavaScript functionality. Bind your click handlers directly in the JS code (note that this solution is using jQuery):
HTML:
<div id="button1">Button1</div>
<div id="button2">Button2</div>
<div id="button3">Button3</div>
<div id="startButton">Start</div>
JS:
function choose1() {
// ...
}
function choose2() {
// ...
}
function choose3() {
// ...
}
$(function() {
$("#button1").click(choose1);
$("#button2").click(choose2);
$("#button3").click(choose3);
});
You can do it in javascript (anything possible with jQuery is possible with plain javascript, since jQuery is written in javascript).
Changing the click handler for the startButton from javascript is very straightforward:
document.getElementById("startButton").onclick = newFunction;
Changing the background image is also pretty simple:
document.getElementById("startButton").style.backgroundImage = "image.png";
Obviously, you should replace newFunction and "image.png" with the function and image you actually want to use respectively.
You can say
function choose1() {
document.getElementById('startButton').onclick = function() {
alert("Button one was originally press");
}
}
jQuery IS javascript. It is just a library of functions/methods that you can call.
To solve your problem, you should write a function that changes the onclick property of your start button, and add the function you write to the onclick of the other buttons.
Like so:
function chooseOne(){
document.getElementById('startButton').onclick="/\*whatever\*/";
}
A technology like what #nbrooks said in the comments that would do this very well is AngularJS
If you give each selector button a class, you can use javascript to interate them and bind a click event. Then you can store in a data property a key which you can lookup in a json object start stores the related action handler and image. Finally in your click handler you can pull these properties and apply them to the start button by setting the onClick handler and background image of the start button.
<div class="startSelector" data-startdataid="1">Button1</div>
<div class="startSelector" data-startdataid="2">Button2</div>
<div class="startSelector" data-startdataid="3">Button3</div>
<div id="startButton">Start</div>
<script>
var startData = {
"1": {
action: function() {
alert("Button 1 was selected");
},
image: "/images/button1.jpg"
},"2": {
action: function() {
alert("Button 2 was selected");
},
image: "/images/button2.jpg"
},"3": {
action: function() {
alert("Button 3 was selected");
},
image: "/images/button3.jpg"
}
}
var changeStartButton = function(e) {
var startDataIndex = e.target.dataset.startdataid
var data = startData[startDataIndex]
document.getElementById("startButton").onclick = data.action
document.getElementById("startButton").style.backgroundImage = data.image
}
items = document.getElementsByClassName("startSelector")
for (var i = 0; i < items.length; i++) {
items[i].addEventListener("click", changeStartButton);
}
</script>
Example
http://jsfiddle.net/Xk8rv/3/

Click toggle with jquery/javascript

I want to click a table element and to have it do x the first click and if clicked again perform Y
<td class='p' id='e1' onclick="myFunction2()"><img src='person2.png'/></td>
Thats what I have for my HTML for one click just now, but I wish to change that so that an item can be selected, then if clicked again for a deselect it would then trigger a different function.
I'm going to assume (you didn't say) that you want the function to be called to alternate with every click:
$('#e1').on('click', function() {
// retrieve current state, initially undefined
var state = $(this).data('state');
// toggle the state - first click will make this "true"
state = !state;
// do your stuff
if (state) {
// do this (1st click, 3rd click, etc)
} else {
// do that
}
// put the state back
$(this).data('state', state);
});
This uses jQuery's .data feature to store the button's click state in the button element itself.
Alternatively, you could use an external variable, but you should enclose the callback in a closure (in this case an immediately invoked function expression) to prevent the variable from becoming a global variable:
(function() {
var state;
$('#e1').on('click', function() {
state = !state;
if (state) {
// do this (1st click, 3rd click, etc)
} else {
// do that
}
});
})();
If the .on call and the state variable declaration are inside a jQuery document.ready handler that would have the same effect.
Pretty basic, let me know if this is close to what you want.
http://jsfiddle.net/WNJ75/6/
<div id="e1">Click Me</div>
.
(function() {
var click_track = 1;
$("#e1").click(function() {
if (click_track == 1)
alert("do something");
else if (click_track == 2) {
alert("do something else and reset click");
click_track = 0;
}
click_track++;
});
})();
demo: http://jsfiddle.net/HJwJf/
Link the toggle method with;
$("button").toggle(function(){
$("body").css("background-color","green");},
function(){
$("body").css("background-color","red");},
function(){
$("body").css("background-color","yellow");}
);
You could create a new atribute on the HTML element named, for example, "clickCount", and use it inside your event handler as a counter.
Let's say you have a button like this one:
<button data-click-count='0' onclick="myFunction(this)">My Button</button>
And you have a function like this:
function myFunction(elt) {
// Gets the clicks count
var count = $(elt).data("click-count");
// Adds one to the click counter
$(elt).data("click-count", ++count);
if (count == 1)
doSomething();
else if (count == 2)
doSomethingElse();
}
Every time you click the button, you'll see an alert with the number of clicks you've made.
You can use the same method and apply it to your case.
Using a state variable. The state variable will swap between the values 0 and 1 on each click. Making use of state we can execute the corresponding function in fn array.
<td class='p' id='e1'><img src='person2.png'/></td>
$("td#e1.p").each(function(){
var state = 1, fn = [myFunction1, myFunction2];
$(this).click(function(){
return fn[state = 1 - state].apply(this, arguments);
});
});
Also, it's preferably to use proper event binding than inline JavaScript.

Categories

Resources