I want to check if the state of show to change the innerText of the button according to it but when I run it the else statment doesnt work
let showBtn = document.querySelector('.show-more');
showBtn.onclick = function () {
let show = false;
if (show === false) {
showBtn.innerText = 'Show Less';
show = true;
} else {
showBtn.innerText = 'Show more';
}
}
showBtn is false on each click in your code. It should not be assigned in the onclick handler. Try this:
let showBtn = document.querySelector('.show-more');
let show = false;
showBtn.onclick = function() {
if (show === false) {
showBtn.innerText = 'Show Less';
} else {
showBtn.innerText = 'Show more';
}
show = !show;
}
<button class="show-more" />Show</button>
Reset the value of show, every click by this way.
let showBtn = document.querySelector('.show-more');
show = false;
showBtn.onclick = function () {
if (show === false) {
showBtn.textContent= 'Show Less';
show = true;
} else {
show = false
showBtn.textContent= 'Show more';
}
}
You should not even be using a variable here in the first place. The accepted answer just creates a new bug as it will break as soon as you have more then one element as the global state would apply to all the elements.
If you want to attach state to elements you can either do it by adding/removing classes or through data attributes (or whatever more specific attribute is applicable).
let showBtn = document.querySelector('.show-more');
showBtn.onclick = function (event) {
// event.target is the clicked element
if (event.target.matches('.expanded')) {
showBtn.textContent= 'Show Less';
else {
showBtn.textContent= 'Show more';
}
event.target.classList.toggle('expanded')
}
In this example the class 'expanded' is used to keep track of the state of the button. This also lets you attach different visual "states" through CSS.
In this case do not assign your state variable let show inside of the calling function. When you do that it will initialize the variable every time you call it. This causes a performance issue (see variable initialization and garbage collection) and depending on what you want to do it will break.
Someone here as already given an answer, but in their answer the variable declaration is in global scope. Most people agree that it's not a good idea to declare global variables, especially with such a general name as show . Later on, as your code base grows, you're likely to run into conflicts and your code will start acting in ways you can't predict. This is probably the most universally agreed upon coding convention. It's a bad habit. Learn how to do it the right way now.
These two StackOverflow answers contain examples that are a good starting point to producing working modular code to control the state of your objects:
wrapper function: https://stackoverflow.com/a/50137216/1977609
This is another way to implement your button: https://stackoverflow.com/a/10452789/1977609
Related
I want to be able to click on an image, have it become big, and then when I click it again, make it go back to being small. I'm trying to use an if/else statement to solve this problem, but I still can't figure it out. This is the JS I have so far:
document.addEventListener("DOMContentLoaded", function(event) {
var thumbnailElement = document.getElementById("smart_thumbnail");
if (thumbnailElement.className === "small") {
thumbnailElement.addEventListener("click", function() {
thumbnailElement.className = "";
});
} else {
thumbnailElement.addEventListener("click", function() {
thumbnailElement.className = "small";
});
}
});
And the HTML for the image:
<img class="small" id="smart_thumbnail" src="http://4.bp.blogspot.com/-QFiV4z\
3gloQ/ULd1wyJb1oI/AAAAAAAAEIg/LE1Kakhve9Y/s1600/Hieroglyphs_Ani-papyrus.jpg">
I'm simply wanting to get rid of the "small" class on the id "smart_thumbnail" to make it big and put the "small" class back to make it small again, but I can only make it big. When I click on it the 2nd time, it doesn't do anything. I've tried an if/else if statement and that didn't work. I looked on here for the same question, but could only find stuff about jQuery. Trying to solve this with JavaScript only.
Any help greatly appreciated. Thanks!
The problem is that the code above will only be run once: After loading your site. So only one condition is fullfilled (thumbnailElement.className === "small")
What you want is something along the lines of:
var thumbnailElement = document.getElementById("smart_thumbnail");
thumbnailElement.addEventListener("click", function() {
if (this.className === "small")
this.className = "";
else
this.className = "small";
});
This will check the class when clicking the image.
Alternatively, you can also use classList.toggle
The DOMContentLoaded event only fires once, that is, when the page is loaded. Instead run your if-statement on a per-click basis.
For example
thumbnailElement.addEventListener("click", function() {
if (thumbnailElement.className === "small") {
thumbnailElement.className = "";
} else {
thumbnailElement.className = "small";
}
});
Now you will register the click event once, but every time it is clicked it will check the classname logic and apply the class name appropriately.
Bootstrap Warnings Image I have two different types of bootstraps alerts (warning and danger). Danger alerts are always suppose to be on the page no matter what. Warning alerts happen when user clicks on the dropdown list carriers it displays a bootstrap warning notification. User has to click on 'x' for it to close. I need it to work when user click anywhere on the page or by clicking on the 'x'.
HomeController.cs
case "Carrier":
var carrierid = (from foo in db.Carriers
where foo.ID == warningid
select foo.WarningID).Single();
if (carrierid != null)
{
warning = (from warnings in db.Warnings
where warnings.IsActive == true && warnings.Id == carrierid
select warnings.WarningBody).SingleOrDefault();
if (warning != null)
{
warning = ("<div class=\"alert alert-warning alert-dismissible\" id=\"myWarning\" role=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">×</span></button><strong>" +
warning + "</strong></div>");
}
else
{
warning = "";
}
}
else
{
warning = "";
}
return Json(warning, JsonRequestBehavior.AllowGet);
default:
break;
warningwriter.js
//// warning display script takes a value of warningid and warningcaller
$(document).ready(function () {
var warningid = 0;
var warningcaller = "Universal";
loadWarnings(warningid, warningcaller);
});
$('#Phones').change(function () {
var warningid = $(this).val();
var warningcaller = "Phone";
loadWarnings(warningid, warningcaller);})
$('#Carriers').change(function () {
var warningid = $(this).val();
var warningcaller = "Carrier";
loadWarnings(warningid, warningcaller);})
function loadWarnings(warningid, warningcaller) {
$.getJSON("../Home/LoadWarnings", { warningID: warningid, warningCaller: warningcaller },
function (warning) {
var select = $('#warnings');
select.append(warning);
});
};
As Martin suggested, it's something you need to do in javascript. I haven't tested this, but it would be something like:
$(document).click(function (event) {
$(".alert").hide();
});
This is basically, clicking anywhere on the page will hide any displayed alert.
Since you have two different types of bootstraps alerts (danger and warning). You have to use ".alert-warning" because that is the one you want to get rid of when user did a mouse click anywhere on page. ".alert" is all of the bootstraps alerts, however, if you need to get rid of a certain type you can call the contextual classes(e.g., .alert-success, .alert-info, .alert-warning, and/or .alert-danger. https://v4-alpha.getbootstrap.com/components/alerts/
$(document).click(function (event) {
$(".alert-warning").hide();
});
$(document).ready(function () {
$("#myWarning").click(function () {
$(".alert").alert("close");
});
});
By doing this, u are making two things wrong:
You are binding the click event to an element, that possibly
doesnt exist when the page is loaded.
You are binding the click
event to a restricted element. This means that the alert wont be
closed when u click anywhere on the page. In this case, only clicks on #myWarning will close the alert.
Finally, you should use what #Bryan already posted :)
Edit:
Assuming that u have a set of alerts that u always want to close on page load, add to this elements a way to identify them, for example a class "close-on-screenclick"
$(document).click(function () {
$(".close-on-screenclick.alert").alert("close");
});
.This should close those elements whenever a click is made on the screen
very new to JS, I'm struggling with my current project: Trying to insert some HTML via a function if a variable = "yes". The variable value will change on a button click.
I've been using firebug to look at the variable value - it doesn't seem to be changing on the button click.
Was hoping someone would be kind enough to help.
I THINK my main issue is with setting the variable value - but I could of course be wrong so I've attached a codepen version for good luck :)
HTML:
<button id="butterbutton" onclick="imageAdd('yes'); ">
<img id="worldimg" src="http://butterybeast.hol.es/world.png"></img>
</button>
JS:
var beast
function imageAdd(choice) {
beast = choice;
}
if (beast = "yes" ) {
function imagemap () {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
}
http://codepen.io/Puffincat/pen/Nrdgrz?editors=1010
You have just a couple of problems with your code. The first is this:
if (beast = "yes") {
In this case, you're assigning "yes" to beast, not comparing it. Change it to
if (beast == "yes") {
Next, your code at the bottom (if (beast == "yes") { ...) is only run at the start. Instead, you want that code to run whenever the variable is updated. Move it into your imageAdd function or somewhere else where you update the UI then call it from imageAdd. While you're at it, remove that imagemap function declaration. It doesn't make sense to declare a function inside of an if statement.
var beast;
function imageAdd(choice) {
beast = choice;
updateUI();
}
function updateUI() {
if (beast == "yes") {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
}
You have a function imagemap wrapped in a conditional but you aren't calling that function.
Also for your conditional, beast will always be null since the conditional is called straight away.
Consider the following adjustment
var beast;
function imagemap () {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
function imageAdd(choice) {
beast = choice;
if (beast === "yes" ) {
imagemap();
}
}
I am creating a Memory Game for a class at school, and I am using Bootstrap and jQuery. See Github. For testing use this jsfiddle, as the github code will change, I've included it if you would like to fork it for your own purposes.
I've constructed the code on the following logic:
Pick with how many cards you want to play.
Cards get loaded and randomized. Each pair have the same class(card* and glyphicon*).
You click on one card, then on another, and if they match they get discarded, else you pick again.
The problem that I'm currently having is with the third step, namely when you click on the third card it shows the previous two, meaning I need to include something to escape the first click events. At least that was my first suggestion for the problem. If you have other suggestions to completely restructure the third step, please don't shy to elaborate why.
// check if picked cards' classes match
jQuery("[class^=card]").click(function() { //picking the first card
jQuery(this).css('color', '#000');
var firstCard = $(this);
var firstCardClass = $(this).find('[class*=glyphicon]').attr('class').split(' ')[1];
jQuery("[class^=card]").click(function() { //picking the second card
var secondCard = $(this);
var secondCardClass = $(this).find('[class*=glyphicon]').attr('class').split(' ')[1];
console.log(firstCardClass);
console.log(secondCardClass);
if (firstCardClass == secondCardClass) {
console.log("yes")
$(firstCard).css('color', '#005d00'); //make them green
$(secondCard).css('color', '#005d00');
setTimeout(function() {
$(firstCard).css('display', 'none'); //discard
$(secondCard).css('display', 'none');
}, 1000);
}
else {
console.log("no");
$(firstCard).css('color', '#cc0000'); //make them red
$(secondCard).css('color', '#cc0000');
setTimeout(function() {
$(firstCard).css('color', '#fff'); //hide again
$(secondCard).css('color', '#fff');
}, 1000);
}
});
});
Note that the icons should be white as the cards, made them grey to see witch ones match without the need of firebug. If you click on more then two cards you will see what the problem is (if I failed to explain it well). I tried with including click unbind events in the end of each statement, but couldn't make it work.
Try your best! Thanks!
EDITED:
Seems I misunderstood the question so here's how I would go about having such game.
First I'll have my cards to have a structure like this:
<span class="card" data-card-type="one">One</span>
I'll use data-card-type to compare whether two cards are of the same type
I'll have a global variable firstCard which is originally null, if null I assign the clicked card to it and if not I compare the clicked card with it and then whether it's a match or not, I assign null to it meaning another pairing has begun.
I'll do all the logic in one onclick, looks weird to have a click listener inside another makes it to somehow look over-complicated.
var firstCard = null;
$('.card').on('click', function() {
$(this).addClass('selected');
if(!firstCard)
firstCard = $(this);
else if(firstCard[0] != $(this)[0]) {
if(firstCard.data('card-type') == $(this).data('card-type')) {
firstCard.remove();
$(this).remove();
firstCard = null;
//$('.card.selected').removeClass('selected');
}
else {
firstCard = null;
$('.card.selected').removeClass('selected');
}
}
});
jsfiddle DEMO
when a card is clicked, you can add a class to that particular card (e.g. classname clickedcard). Whenever you click another card you can test if there are 2 cards having this clickedcard class. If so, you can take action, for example remove all the clickedcard classes and add one again to the newly clicked one.
In pseudo code I would do it something like this:
jQuery("[class^=card]").click(function() {
if (jQuery('.clickedcard').length == 2) {
// two cards where clicked already...
// take the actions you want to do for 2 clicked cards
// you can use jQuery('.clickedcard')[0] and jQuery('.clickedcard')[1]
// to address both clicked cards
jQuery('.clickedcard').removeClass('clickedcard');
} else {
// no card or only one card is clicked
// do actions on the clicked card and add classname
jQuery(this).addClass('clickedcard');
}
});
You could use `one' (to bind an event once):
$("[class^=card]").one(`click', firstCard);
function firstCard() { //picking the first card
$(this).css('color', '#000');
var firstCard = $(this);
var firstCardClass = $(this).find('[class*=glyphicon]').attr('class').split(' ')[1];
$("[class^=card]").one('click', secondCard);
function secondCard() { //picking the second card
var secondCard = $(this);
var secondCardClass = $(this).find('[class*=glyphicon]').attr('class').split(' ')[1];
console.log(firstCardClass);
console.log(secondCardClass);
if (firstCardClass == secondCardClass) {
console.log("yes")
$(firstCard).css('color', '#005d00'); //make them green
$(secondCard).css('color', '#005d00');
setTimeout(function() {
$(firstCard).css('display', 'none'); //discard
$(secondCard).css('display', 'none');
}, 1000);
}
else {
console.log("no");
$(firstCard).css('color', '#cc0000'); //make them red
$(secondCard).css('color', '#cc0000');
setTimeout(function() {
$(firstCard).css('color', '#fff'); //hide again
$(secondCard).css('color', '#fff');
}, 1000);
}
$("[class^=card]").one(`click', firstCard);
}
}
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.