Why does jQuery click event only work once? - javascript

I am trying make speed units toggle when clicking. However, this only works once. I have run out of things to try. I also tried .click(), .live(), .toggle() (which only made it disappear and reappear), etc.
HTML:
<li id="wind">Wind speed</br>
<p class='windSpeedKm'></p>
</li>
Javascript:
var click = true;
$('#wind').on('click', function() {
if (click = false) {
$('#wind').html(function() {
$(this).html("Wind speed<br>" + windKm);
click = true;
});
} else if (click = true) {
$('#wind').html(function() {
$(this).html("Wind speed<br>" + windMi);
click = false;
});
}
});

This isn't exactly what you asked for, but this will save you so much time it is unbelievable. It has an auto convert function built in so you don't have to manually update both numbers. It doesn't replace unnecessary to replace html.
<li id="wind">Wind speed</br>
<p class='windSpeedKm' km="500">500</p>
</li>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function toMiles(km) {
return parseFloat(km) * 0.62137;
}
$('#wind').on('click', function() {
console.log($(this).attr("km"));
windSpeedKm = $(this).find(".windSpeedKm");
km = windSpeedKm.attr("km");
if (km === windSpeedKm.html()) {
windSpeedKm.html(toMiles(km));
} else {
windSpeedKm.html(km);
}
});
</script>

There are a few syntax issues with the code:
var click = true;
$('#wind').on('click', function() {
if (click) {
$(this).html("Wind speed<br>" + windKm):
click = true;
} else {
$(this).html("Wind speed<br>" + windMi);
click = false;
}
});
Note: there isn't any need to set click = true or click = false in your example as falling into the if statement by checking the click assignment value, this will already be true! You would only do this if you wanted to toggle the boolean to false after confirming it was true.

click = true should be click == true;

Related

Scripts collide with each other - JavaScript

I've got a page wich is, basically, a list of divs; it doesn't matter how they're structured, suffice it to say that they're all visible by default. There are buttons on the page that lets you sort through them thanks to a java script. For example, if you click on the button "complete", the page shows only the divs containing the code
<div class="ended">complete</div>
while if you push on the "show all" button, it returns to show them all. (The structure is something like
<div class="entry">
<p>something</p>
<div class="ended">complete</div>
et cetera </div>
I've recently decided to add a new button, that picks a random div through them all. It all works well, except that when you try to show them all again after picking a random one, it doesn't work.
I'm not really all that familiar with JavaScript and JQuery (the random script I adapted from a script I found here), so I dont' understand what's wrong.
This is the code for (one of) the sorting script:
$('#completed').click(function() {
featureList.filter(function(item) {
if (item.values().ended == "complete") {
return true;
} else {
return false;
}
});
return false;
});
And this is the code for the "show all" button:
$('#filter-none').click(function() {
featureList.filter();
return false;
});
Finally, this is the code for the "random" button:
$(document).ready(function () {
$('#random').click(function () {
var E = document.getElementsByClassName("entry");
var m = E.length;
var n = parseInt(Math.random() * m);
for (var i = m - 1; i >= 0; i--) {
var e = E[i];
e.style.display = 'none';
}
E[n].style.display = '';
});
});
Hard to give an answer without knowing what's going on inside the .filter-function but based on what you've provided this could work:
$('#random').click(function () {
var entries = document.getElementsByClassName("entry");
var numEntries = entries.length;
var random = Math.floor(Math.random() * numEntries);
var counter = numEntries;
featureList.filter(function(item) {
counter--;
if (counter === random) {
return true;
} else {
return false;
}
});
return false;
}
I'm assuming the elements for which false is returned inside .filter are hidden somehow.
Since 'Show all' and 'Show only completed' is working, using the 'Show only completed'-way of hiding the wrong elements in 'Show random' should work.

HTML / Javascript - Trouble changing text when clicked

So I have some HTML code here:
<body>
<b style="font-size: 26px;">How the game works</b>
<u id="HowToPlay_HideShow" style="color: #9FF;">[hide]</u><br>
</body>
And I also used Javascript to turn the hide text into show, and show back into hide when clicked on.
<script>
var HowGameWorks_Hidden = false;
document.getElementById("HowToPlay_HideShow").onclick = function () {
if (HowGameWorks_Hidden == false) {
document.getElementById("HowToPlay_HideShow").innerHTML = "[show]";
HowGameWorks_Hidden = true;
}
if (HowGameWorks_Hidden == true) {
document.getElementById("HowToPlay_HideShow").innerHTML = "[hide]";
HowGameWorks_Hidden = false;
}
}
</script>
This, however, does not seem to work. Clicking on the hide and show text has no effect at all. So I tried removing this piece of code:
if(HowGameWorks_Hidden == true) {
document.getElementById("HowToPlay_HideShow").innerHTML = "[hide]";
HowGameWorks_Hidden = false;
}
And it correctly turns the hide text into show when I click it (but, of course, does not turn the show text back into hide).
So how do I get my code working?
This is because your second if statement will always get triggered if your first one does, since you set HowGameWorks_Hidden to true in it. You need to use an else:
if(HowGameWorks_Hidden == false) {
document.getElementById("HowToPlay_HideShow").innerHTML = "[show]";
HowGameWorks_Hidden = true;
}
else if(HowGameWorks_Hidden == true) {
document.getElementById("HowToPlay_HideShow").innerHTML = "[hide]";
HowGameWorks_Hidden = false;
}

Use the same keypress to show a div and hide another, repeatedly, using Javascript

Lets call the 2 divs in question div1 and div2.
What I'm trying to do is use the enter key to show div1 and hide div2 (if div2 is currently visible) and vice-versa. Right now I have the code so that pressing enter will show div1 and hide div2, but to go back to having div2 shown and div1 hidden you have to use the shift key. The way it is now works, but I would like it so I only have to press enter each time I want the divs to alternate.
Here is the javascript code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var keys = [];
var code = [13];
var keys1=[];
var code1 = [16];
$(document).keydown(function(keyEvent) {
keys.push(keyEvent.keyCode);
keys1.push(keyEvent.keyCode);
if ( keys.length > code.length ) {
keys.shift();
}
if ( keys1.length > code1.length ) {
keys1.shift();
}
if ( keys.toString() == code.toString() ) {
showAns();
}
if ( keys1.toString() == code1.toString() ) {
hideAns();
}
});
});
</script>
Any idea how to accomplish what I'm asking?
Try this sample of what you want to achieve:
var toShow = true;
$(document).keydown(function(keyEvent) {
if(keyEvent.keyCode == 13){
$('#div1').toggle(toShow);
$('#div2').toggle(!toShow);
toShow = !toShow;
}
});
I'll give you a nudge in the right direction, but won't supply you the answer outright.
You need to find a way to check the property of your elements visibility ( How do I check if an element is hidden in jQuery? This might help you!), and add that to your conidtion like so:
if(KeyIsPressed && element.IsVisible)
{
HideElement
}
else if(KeyisPressed)
{
ShowElement
}
Without getting too fancy, you can use a 'state' variable to hold that information, and then synchronize that to the DOM:
var state = {
"div1": true,
"div2": false,
};
synchronizeState();
$(document).on("keydown", function(event) {
if(event.which === 13) {
state.div1 = !state.div1;
state.div2 = !state.div2;
synchronizeState();
}
});
function synchronizeState() {
if(state.div1) {
$("#div1").show();
} else {
$("#div1").hide();
}
if(state.div2) {
$("#div2").show();
} else {
$("#div2").hide();
}
}
Working example: http://jsbin.com/eJiPavO/1/

Compare onclick action of two html button using javascript

I have this two HTML Form buttons with an onclick action associated to each one.
<input type=button name=sel value="Select all" onclick="alert('Error!');">
<input type=button name=desel value="Deselect all" onclick="alert('Error!');">
Unfortunately this action changes from time to time. It can be
onclick="";>
or
onclick="alert('Error!');"
or
onclick="checkAll('stato_nave');"
I'm trying to write some javascript code that verifies what is the function invoked and change it if needed:
var button=document.getElementsByName('sel')[0];
// I don't want to change it when it is empty or calls the 'checkAll' function
if( button.getAttribute("onclick") != "checkAll('stato_nave');" &&
button.getAttribute("onclick") != ""){
//modify button
document.getElementsByName('sel')[0].setAttribute("onclick","set(1)");
document.getElementsByName('desel')[0].setAttribute("onclick","set(0)");
} //set(1) and set(0) being two irrelevant function
Unfortunately none of this work.
Going back some steps I noticed that
alert( document.getElementsByName('sel')[0].onclick);
does not output the onclick content, as I expected, but outputs:
function onclick(event) {
alert("Error!");
}
So i guess that the comparisons fails for this reason, I cannot compare a function with a string.
Does anyone has a guess on how to distinguish which function is associated to the onclick attribute?
This works
http://jsfiddle.net/mplungjan/HzvEh/
var button=document.getElementsByName('desel')[0];
// I don't want to change it when it is empty or calls the 'checkAll' function
var click = button.getAttribute("onclick");
if (click.indexOf('error') ) {
document.getElementsByName('sel')[0].onclick=function() {setIt(1)};
document.getElementsByName('desel')[0].onclick=function() {setIt(0)};
}
function setIt(num) { alert(num)}
But why not move the onclick to a script
window.onload=function() {
var button1 = document.getElementsByName('sel')[0];
var button2 = document.getElementsByName('desel')[0];
if (somereason && someotherreason) {
button1.onclick=function() {
sel(1);
}
button2.onclick=function() {
sel(0);
}
}
else if (somereason) {
button1.onclick=function() {
alert("Error");
}
}
else if (someotherreason) {
button1.onclick=function() {
checkAll('stato_nave')
}
}
}
Try casting the onclick attribute to a string. Then you can at least check the index of checkAll and whether it is empty. After that you can bind those input elements to the new onclick functions easily.
var sel = document.getElementsByName('sel')[0];
var desel = document.getElementsByName('desel')[0];
var onclick = sel.getAttribute("onclick").toString();
if (onclick.indexOf("checkAll") == -1 && onclick != "") {
sel.onclick = function() { set(1) };
desel.onclick = function() { set(0) };
}
function set(number)
{
alert("worked! : " + number);
}
working example: http://jsfiddle.net/fAJ6v/1/
working example when there is a checkAll method: http://jsfiddle.net/fAJ6v/3/

jQuery if (x == y) not working

So, I have some faux checkboxes (so I could style them) that work with jQuery to act as checked or not checked. There are a number of faux checkboxes in my document, and for each one I have a click function:
var productInterest = [];
productInterest[0] = false;
productInterest[1] = false;
productInterest[2] = false;
// here is one function of the three:
$('#productOne').click(function() {
if (productInterest[0] == false) {
$(this).addClass("checkboxChecked");
productInterest[0] = true;
} else {
$(this).removeClass("checkboxChecked");
productInterest[0] = false;
}
});
The problem seems to be that there is an error in the if statement, because it will check, but not uncheck. In other words it will add the class, but the variable won't change so it still thinks its checked. Anybody have any ideas? Thanks for your help.
UPDATE: So, I need to show you all my code because it works in the way I supplied it (thanks commenters for helping me realize that)... just not in the way its actually being used on my site. so below please find the code in its entirety.
Everything needs to happen in one function, because the UI and data for each checkbox need to be updated at once. So here is the complete function:
$('input[name=silkInterest]').click(function() { // they all have the same name
var silkInterest = [];
silkInterest[0] = false;
silkInterest[1] = false;
silkInterest[2] = false;
if ($(this).is('#silkSilk')) { // function stops working because the .is()
if (silkInterest[0] == false) {
$(this).addClass("checkboxChecked");
silkInterest[0] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[0] = false;
}
alert(silkInterest[0]);
}
if ($(this).is('#silkAlmond')) {
if (silkInterest[1] == false) {
$(this).addClass("checkboxChecked");
silkInterest[1] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[1] = false;
}
}
if ($(this).is('#silkCoconut')) {
if (silkInterest[2] == false) {
$(this).addClass("checkboxChecked");
silkInterest[2] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[2] = false;
}
}
var silkInterestString = silkInterest.toString();
$('input[name=silkInterestAnswer]').val(silkInterestString);
// This last bit puts the code into a hidden field so I can capture it with php.
});
I can't spot the problem in your code, but you can simply use the class you're adding in place of the productInterest array. This lets you condense the code down to a single:
// Condense productOne, productTwo, etc...
$('[id^="product"]').click(function() {
// Condense addClass, removeClass
$(this).toggleClass('checkboxChecked');
});
And to check if one of them is checked:
if ($('#productOne').hasClass('checkboxChecked')) {...}
This'll make sure the UI is always synced to the "data", so if there's other code that's interfering you'll be able to spot it.
Okay, just had a palm to forehead moment. In regards to my revised code- the variables get reset everytime I click. That was the problem. Duh.

Categories

Resources