Display Content only if a user "wins" - javascript

having a bit of trouble.
im trying to creat a play again button the appears only when the user wins,
i've set the condition of the div to visibility:none when the user won,
else its in display:none
however, the button always appears, right from the start, any advice?
the audio plays correctly, only when the user wins.
so i got this piece of code in html:
<div id="Again">
<button type="button" onclick="toggle_visibility">Play Again</button>
</div>
and the following in js:
function toggle_visibility(id) {
var x = document.getElementById('Again');
if (TOTAL_COUPLES_COUNT === flippedCouplesCount) {
audioWin.play();
x.style.display = 'block';}
else {
x.style.display = 'none';
}

The initial display state of the button should be none. Here's a skeleton snippet that may help you along:
const button = document.querySelector("button");
const input = document.querySelector("input");
const inputHandler = evt => {
if (+evt.target.value == guessValue) {
button.classList.replace("hidden", "visible");
} else {
button.classList.replace("visible", "hidden");
}
};
let guessValue = Math.ceil(Math.random() * 10);
button.addEventListener("click", () => {
button.classList.replace("visible", "hidden");
input.value = "";
guessValue = Math.ceil(Math.random() * 10);
});
input.addEventListener("change", inputHandler);
input.addEventListener("keyup", inputHandler);
button.hidden {
display: none
}
button.visible {
display: inline-block
}
<input type="number" max="10" min="1"> Guess a number (1 - 10)
<button class="hidden">Again?</button>

The button is visible since the beginning because it has neither an "hardcoded" style attribute which says to hide it or a CSS proprerty which does the same. The JS code which "toggles" the button is only triggered when pressed, so it has no effect as the page loads.

Related

Remove inline styles when clicking on button

The following happens to me:
I have made a slider with the next and previous arrows that works correctly. The case is that I have a button called "see all" in which when I press it, it puts a display none to the previous and next arrows and shows everything that is in the slider (that is to say, when I press the button, it shows everything and "deactivates" the slider).
The problem is that when you press the button again to stop displaying everything and return to "slider mode", the previous and next buttons do not go through the slider.
The slider is putting the active class and removing it to show what is inside. But once I have used the button of "see all" it is added in line a "display: none" and although I give to the arrows of previous or following and the class active is put correctly it remains the style="display:none;" inline in the html and it stops working.
The code of the button that shows everything:
var btnMore = document.querySelector(".btn-panes");
var boxes = document.querySelectorAll("#slider .box-panes");
var aLeft = document.querySelector("#slider .left");
var aRight = document.querySelector("#slider .right");
var btnMoreActivated = false;
btnMore.addEventListener("click", function(){
if(!btnMoreActivated){
for(var i=0; i<boxes.length; i++ ){
document.querySelector("#slider").style.flexWrap = "wrap";
boxes[i].style.display = "flex";
aLeft.classList.add("ocultar");
aRight.classList.add("ocultar");
}
btnMoreActivated = true;
} else {
for(var i=1; i<boxes.length; i++ ){
boxes[i].style.display = "none";
document.querySelector("#slider").style.flexFlow = "nowrap";
aLeft.classList.remove("ocultar");
aRight.classList.remove("ocultar");
}
btnMoreActivated = false;
}
});
The slider code (it works) but just to show you what it does in case you need to add something to fix the problem:
const items = document.querySelectorAll('#slider .box-panes');
const itemCount = items.length;
const nextItem = document.querySelectorAll('.right img');
const previousItem = document.querySelectorAll('.left img');
var count = 0;
function shorHide(){
switch (key) {
case value:
break;
default:
break;
}
}
function showNextItem() {
items[count].classList.remove('active');
if(count < itemCount - 1) {
count++;
} else {
count = 0;
}
items[count].classList.add('active');
}
function showPreviousItem() {
items[count].classList.remove('active');
if(count > 0) {
count--;
} else {
count = itemCount - 1;
}
items[count].classList.add('active');
}
function keyPress(e) {
e = e || window.event;
if (e.keyCode == '37') {
showPreviousItem();
} else if (e.keyCode == '39') {
showNextItem();
}
}
nextItem[0].addEventListener('click', showNextItem);
previousItem[0].addEventListener('click', showPreviousItem);
document.addEventListener('keydown', keyPress);
This is because inline styles are the most specific type of style to add and therefore the most difficult to override. The simplest solution is to not use inline styles and instead use a class that can be added or removed as needed.
Here's a simple example that you can use to replace: boxes[i].style.display = "none";
// Get the elements that need to be hidden/shown into a collection
let btns = document.querySelectorAll(".nav");
document.getElementById("hide").addEventListener("click", function(e){
// Loop over the collection
btns.forEach(function(el){
el.classList.add("hidden"); // Apply the hidden class
});
});
document.getElementById("show").addEventListener("click", function(e){
btns.forEach(function(el){
el.classList.remove("hidden"); // Remove the class
});
});
.hidden { display:none; }
<button id="hide">Hide Buttons</button>
<button id="show">Show Buttons</button>
<button class="nav"><<</button> <button class="nav">>></button>

How make input RESET Button?

How make input RESET Button?
INFO:
Hi I'm trying to do that if I click on my input which has the ID search-input so that if I write something in the input then class cancel which is the cross that resets the value it's like <button type =" reset "> so if I write something so that it appears to me sodisplay: block;and if I delete or input it won't have a value to dodisplay: none;and I would like to do all this to make it work even if the user doesn't have Javascript so I would like to do it in PHP version but I don't know what I have so far I only have this code which shows the icon when something is in the input but unfortunately the code has stopped working and especially when I delete the input via the button so the icon doesn't disappear for more information be sure not to be afraid to ask.
const input = document.getElementById("search-input")
const button = document.getElementById("cancel")
const icon = document.getElementById("icon")
input.addEventListener('keyup', test);
button.addEventListener("button", test)
function test() {
let isShown = false
if (input.value.trim() == "" || isShown == false) {
icon.style.display = "none"
isShown = true
} else {
icon.style.display = "flex"
}
}
PS: Everything was translated by Google translator if there was a mistake or you did not understand something write and I will definitely tell you how it should be thought in advance thank you very much for your help.
I think Uttam Nath's answer was close to what you wanted but not exactly. This may work better:
EDIT: Alright I changed the code a bit and I added the HTML with it so there is no confusion.
<body>
<input type="text" id="search-input">
<button type="button" id="cancel">Cancel</button>
<div id="icon" style="background-color: green; width: 50px; height: 50px; display: none;"></div>
</body>
<script>
const input = document.getElementById("search-input");
const button = document.getElementById("cancel")
const icon = document.getElementById("icon");
input.addEventListener('keyup', changeIconDisplay);
button.addEventListener('click', () => {
input.value = '';
changeIconDisplay();
});
function changeIconDisplay() {
if (input.value.trim() == "" ) {
icon.style.display = "none";
} else {
icon.style.display = "flex";
}
}
</script>

Disable or enable buttons if input condition met in JS, While input is auto-generated

i'm newbie in JS.
as in the title, I want to create a disable button when the condition is met based on the following code:
<input class="input" type="text">
<button class="button">Click Me</button>
<script>
let input = document.querySelector(".input");
let button = document.querySelector(".button");
button.disabled = true;
input.addEventListener("change", stateHandle);
function stateHandle() {
if(document.querySelector(".input").value === "") {
button.disabled = true;
} else {
button.disabled = false;
}
}
</script>
value on input is auto generated after 500ms. the code above works if after the input value appears and then I enter any number. what I want is when the input value appears then the button will automatically be in the enable position.
Based on #David's answer, I added new Events and dispatch them later.
This is the updated code :
<script >
let input = document.querySelector("#input");
let button = document.querySelector("#button");
button.disabled = true; //setting button state to disabled
const event = new Event("change"); //adding new event
input.addEventListener("change", stateHandle);
function stateHandle() {
var t = document.getElementById("jarak").value,
check = "luar";
if (new RegExp('\\b' + check + '\\b').test(t)) {
button.disabled = true; //button remains disabled
} else {
button.disabled = false; //button is enabled
}
}
setTimeout(function() {
input.dispatchEvent(event); //dispatching event after 700ms
}, 700);
</script>

How can I write this javascript code cleaner?

all
I am currently practicing my coding skills and am making a simple footer selection webpage.
I have four footers with different looks that are set to "display:none" initially. Then, I have four buttons, each one corresponding to its footer type. When the button is clicked, it displays the footer.
Now I just want to know how do I write a cleaner Javascript than what I currently have. Thank you as always.
var footer1 = document.getElementById('footer1');
var footer2 = document.getElementById('footer2');
var footer3 = document.getElementById('footer3');
var footer4 = document.getElementById('footer4');
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
var btn3 = document.getElementById('btn3');
var btn4 = document.getElementById('btn4');
btn1.onclick = function(e) {
console.log('You clicked button1');
e.preventDefault();
footer1.style.display = 'block';
footer2.style.display = 'none';
footer3.style.display = 'none';
footer4.style.display = 'none';
}
btn2.onclick = function(e) {
console.log('You clicked button2');
e.preventDefault();
footer2.style.display = 'block';
footer1.style.display = 'none';
footer3.style.display = 'none';
footer4.style.display = 'none';
}
btn3.onclick = function(e) {
console.log('You clicked button3');
e.preventDefault();
footer3.style.display = 'block';
footer2.style.display = 'none';
footer1.style.display = 'none';
footer4.style.display = 'none';
}
btn4.onclick = function(e) {
console.log('You clicked button4');
e.preventDefault();
footer4.style.display = 'block';
footer2.style.display = 'none';
footer3.style.display = 'none';
footer1.style.display = 'none';
}
You can just use Arrays like this:
let buttons = [ 'btn1', 'btn2', 'btn3', 'btn4' ];
let footers = [ 'footer1', 'footer2', 'footer3', 'footer4' ];
buttons.forEach((btn, index) => {
// Please note that you might want to use addEventListener instead of onclick
document.getElementById(btn).addEventListener('click', (event) => {
event.preventDefault();
let button = 'button' + (index + 1);
alert('You clicked ' + button);
footers.forEach((footer, index_f) => {
let f = document.getElementById(footer);
if(index_f === index) {
f.style.display = 'block';
}
else {
f.style.display = 'none';
}
});
});
});
To make things even more interesting, you can play with querySelectorAll and custom attributes. You could, for example, add the classes custom-button to your buttons and custom-footer to your footers, and on each button add a data-footer attribute pointing to the id of the corresponding footer. Then, you could do this:
document.querySelectorAll(".custom-button").forEach((button) => {
button.addEventListener('click', (event) => {
document.querySelectorAll(".custom-footer").forEach(footer => footer.style.display = 'none');
let footer = button.getAttribute("data-footer");
document.getElementById(footer).style.display = 'block';
});
});
Quite shorter.
There is a common way to do this.
Share a class (foo) between all of the elements you want to group into your show/hide radio button-like functionality.
Then use one function, like
function handler = function(e) {
var foos = document.getElementsByClass("foo");
// make all foos display="none"
var target = targets[e.target]; //get the footer to show from the target button
target.style.display = "block";
}
You can use attribute selector to loop over elements.
[attributeName="value"]
^: Means starts with
$: Ends with
This way, your logic is generic and does not requires you to maintain any list of IDs
Idea:
You can create a pattern where every button id will correspond to visibility to necessary footer. Better idea would be to use data attribute(data-<attr name>) but you can work with ids for now.
Loop over all the buttons and add handler using addEventListener. onClick is a property, so assignment will erase/ override previous value. You can either have inline anonymous function or a named function if you have too many buttons.
In this handler, loop over all footers and hide them.
Fetch index using this.id and show necessary footer. Its always better to use classes for such actions instead of setting styles.
var buttons = document.querySelectorAll('[id^="btn"]');
Array.from(buttons, (button) => {
button.addEventListener('click', function(event) {
const footers = document.querySelectorAll('[id^="footer"]');
Array.from(footers, (footer) => footer.style.display = 'none' );
const index = this.id.match(/\d+/)[0];
document.getElementById(`footer${index}`).style.display = 'block';
})
})
div[id^="footer"] {
width: 100px;
height: 100px;
border: 1px solid gray;
margin: 10px;
}
<div id="footer1"> Footer 1 </div>
<div id="footer2"> Footer 2 </div>
<div id="footer3"> Footer 3 </div>
<div id="footer4"> Footer 4 </div>
<button id="btn1"> Button 1 </button>
<button id="btn2"> Button 2 </button>
<button id="btn3"> Button 3 </button>
<button id="btn4"> Button 4 </button>
References:
Attribute Selector - MDN

create a button that shows or hides a div depending on whether it is currently showing

I'm fairly new in with JS and was wondering, if
there is a more cleaner way of writing this code?
I'm trying to create a button that shows or hides a div depending on whether it is currently showing.
Many Thanks in Advance
Anne
var button = document.getElementById('button');
var hideText = document.getElementById('output').className = 'hide';
button.addEventListener('click', ()=>{
if(hideText){
document.getElementById('output').className = 'unhide';
hideText = false;
}else{
document.getElementById('output').className = 'hide';
hideText = true;
}
})
CSS
.hide{display: none;}
.unhide{display: block;}
Just use a single class (e.g. unhide) and make it invisible by default. Then do
button.addEventListener('click', () => {
document.getElementById('output').classList.toggle('unhide');
}
You can just toggle the classes
button.addEventListener('click', () => {
document.getElementById('output').classList.toggle('hide');
}
You can remove the extra variable hideText and also the extra css if you implement like this
var x = document.getElementById("output");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
In jquery the are other simpler possible way like toggle, hide, show.

Categories

Resources