Javascript toggle if else

if else statement reacting to a toggle class Javascript

Last question I’m asking. I’m trying yo get my audio to play when my classes toggle but I don’t know what if else statement to use. html:

 #sound < width: 3em; height: 3em; margin: 5em 1em; position: absolute; display: flex; >#sound div < width: 0.3em; background: black; border: 1px solid white; border-radius: 2em; >.one < margin-top: 1em; height: 1em; transition:all 300ms ease-in-out; >.oneanimated
var backgroundtelegrafisch = document.getElementById("backgroundtelegrafisch"); var sound = document.getElementById("sound"); var one = document.getElementsByClassName("one"); var oneanimated = document.getElementsByClassName("one"); function animatie () < one[0].classList.toggle("oneanimated"); two[0].classList.toggle("twoanimated"); three[0].classList.toggle("threeanimated"); if (one == oneanimated)< backgroundtelegrafisch.play(); >else < backgroundtelegrafisch.pause(); console.log("test"); >> sound.addEventListener("click", animatie); 

There are two reasons why this might be happening. Either one == oneanimated , so your code will enter the if conditional rather than the else conditional, or you’re never actually calling the animatie() function, meaning you won’t see any output. My guess is the latter, as it’s one character off animate — you may have made a typo when naming/calling the function.

No, I am calling the function (using a clickevent). Animatie is the dutch word for animate. (sorry for the confusion)

Читайте также:  Nginx 404 index html

Can you please update your question so that it shows all relevant code in a minimal, complete, and verifiable example? There are multiple reasons why it might not be working, and it’s impossible to tell which from your above code. Are you getting any errors in the console? What happens if you console.log(‘test’) as the first line of the function?

1 Answer 1

The reason you’re not seeing anything in the console is because, well, the if always succeeds. You do this:

var one = document.getElementsByClassName("one"); var oneanimated = document.getElementsByClassName("one"); 

. which means one and oneanimated are exactly the same as each other. You then do this:

Can you see the problem now? You’re comparing one and oneanimated , and since they’re the same (as we saw earlier) the code will always hit the backgroundtelegrafisch.play(); line instead of going into the else .

Instead of trying to compare one to oneanimated , you should instead do this:

if (one[0].classList.contains("oneanimated")) < backgroundtelegrafisch.play(); >else

The contains method of classList checks if the element has the specified class.

Источник

Example code for toggling if/else statements in JavaScript

To prevent it, return false. Here are two solutions: Firstly, in your HTML templates, set ncaa to active instead of toggling it during page load. Secondly, utilize one of the element’s properties (e.g., its data attribute) to hold the toggle value for you.

If else statement reacting to a toggle class Javascript

The console is empty because the if has a consistently successful outcome, and as a result, you are executing the following action.

var one = document.getElementsByClassName("one"); var oneanimated = document.getElementsByClassName("one"); 

Both one and oneanimated are identical to each other, implying that you should proceed with the following steps.

Is the issue clear to you? When you compare one with oneanimated , the code will consistently execute the backgroundtelegrafisch.play(); line, rather than entering the else block, since they’re identical (as previously observed).

Rather than attempting a comparison between one and oneanimated , it is advisable to carry out the following action.

if (one[0].classList.contains("oneanimated")) < backgroundtelegrafisch.play(); >else

The presence of a particular class in an element is verified using the contains technique of classList .

Need to toggle a Boolean in a if else statement, Okay, I need to be able to call a method and toggle a boolean value so that the return is different every time I need to be able to call the method 9 time’s and each time switch between returning X, O, X, O, X, O, X, O, X

How do I change an if-else statement into a toggle?

Create a globally accessible object to store the functions.

functions = <>; functions[true] = black; functions[false] = color; black = true 

And then invert your state flag:

Although it meets your extremely capricious demands, the solution is unattractive.

Instead of declaring a toggle variable beforehand, you may utilize a property of the anchor element to carry the toggle value for you. For instance, the ID property can be used for this purpose. By doing so, all the required code can be included in a single ondoubleclick event.

 

I CHANGE COLORS!

Double click here

The IDs have been modified to exclude spaces. This approach can be applied to utilize any other available anchor element attributes that are not required in your code but can serve as a toggle switch.

You can use the ternary operator:

this.style.color = this.style.color == '#000000' ? '#ff0000' : '#000000'; 

It is recommended to avoid using inline event handlers.

How to loop if/else statements (JavaScript)?, You can use a while loop and a variable to do this. I would also get rid of all these if statements and replace with a switch statement. var exit = false; while (!exit) < switch (begin) < case 'look around': alert ('To your right is the door.Left is the dresser with some pictures on it and a mirror on the wall.

Javascript code executing both if and else blocks

It seems like your click event is propagating upwards based on what you’ve described. To stop this, use «return false».

$drillDownListItem.live('click', function() < options.$this = $(this); if(!$(this).children("ul").is(":visible")) < showChildren(options); >else < hideChildren(options); >return false; >); 

How to toggle class using jquery if else statement?, If there are more than 2 values for «myvar» like layout1, layout2, layout3 and so on.. and different css classes relative to each myvar value,then how can we toggle the css class? – galexy Jan 23, 2013 at 16:08

If Else Statements, Javascript Toggle, Liquid / Ruby Language

To avoid toggling ncaa at page load, consider setting it to active in your html templates by adding a .active class. Then, in your stylesheets, use .active or a similar option. If possible, use data-* attributes in your buttons to avoid the need for regex to obtain a matching id.

So your html will be like this

The logic of the five carousel button/div is shared, which means that you only need to write one listener that applies to all of them.

 $("#carousel-filters").on("click", "button", function() < $("#carousel-filters button").removeClass("active"); $(this).addClass("active"); $(".teams-carousel").hide(); // Use data attributes to get corresponding div id var $(id).toggle(); >);

My knowledge of ruby/liquid is limited, but I believe you can utilize a for loop structure to create a singular block that can be looped through with varying values.

To avoid repetition, a possible solution is to create a liquid variable that can be utilized in the Javascript class/id selectors. The liquid can be inserted at the beginning of the page.

Upon inclusion, a fresh variable named sport_league will be at your disposal. This variable stands for the shared sequence of characters employed to denote a specific sport or carousel. As a result, you can effortlessly showcase the desired carousel by appending the following Javascript code.

The aforementioned code written in Javascript only runs once and incorporates the variable sport_league to counteract the CSS of display: none and display the suitable carousel.

Raphael.js — if / else statement not toggling on click, Currently it switches between them fine (the IF part), but when I click on the same box to toggle it off if doesn’t work (the «else if» part doesn’t seem to work). I think I need to restructure the if-statement. Any help is greatly Here is

Источник

Toggle between JavaScript if-else statements using JavaScript

Alternative 2: Consider utilizing jQuery. Alternative 3: The issue stems from the fact that HTMLElement.style.background returns a color string in RGB format. The initial part of the code changes the button color to #198B07, but the following click does not seem to trigger the «else» statement that sets the color to #2A303C.

Javascript else of toggle

dreamweaver screen cap

As I progress with my project, I’ve encountered a problem with the toggling of number 2. Unfortunately, my attempts to resolve the issue have been unsuccessful so far.

document.getElementsByClassName("buttons")[1].onmousedown= function()< colorchange(); >; > function colorchange() < /*var background = function blue()else < if (getElementsByClassName("buttons")[1] == "5px blue solid") < document.getElementsByClassName("buttons")[1].style.background = "5px #c90 solid"; >> > 
window.onload = init; var stateTwo = false, colorsThree = ['#cc9900','#1e3a03','#611790']; function init() < var btns = document.getElementsByClassName("buttons"); btns[0].onmousedown = btns[0].onmouseup = funcOne; btns[1].onclick = funcTwo; btns[2].onclick = funcThree; >function funcOne(e) < this.style.background = ( e.type == 'mouseup' )? '#336600' : '#bd270a'; >function funcTwo(e) < stateTwo = !stateTwo; this.style.borderColor = stateTwo ? '#0c1583' : '#cc9900'; >function funcThree()
JS Fiddle Demo
if (getElementsByClassName("buttons")[1] == "5px blue solid") 
if (getElementsByClassName("buttons")[1].style.border == "5px solid blue") 

Javascript — If Statement and toggleClass, Else li 3 is active (county layer), then de-activate li item 2 (state layer) I know it’s possible in jQuery I’m just having trouble referencing the individual …

Else part of If Else not working in my Javascript Toggle button

In my ASP.net environment with c#, javascript, and vs2013 express, I aim to use if/else JS logic to switch the background color of a button that I have.

The first part of the statement successfully modifies the button color to #198B07, but the «else» property doesn’t seem to activate upon subsequent clicks to set the color to «#2A303C». The button’s default color is gray. Could it be getting «reset» on the second click, causing the initial «if» condition to be true again? This seems to be the case, as the color remains #198B07 for all subsequent clicks once it has been changed.

Any idea what I’m doing wrong?

The code style.background does not result in a hexadecimal color, instead it gives back RGB values. In order to make a correct comparison, you should modify the if statement to compare the RGB values.

if (document.getElementById("test").style.background != 'rgb(25, 139, 7)') 

Check out the example on jsfiddle to see how the background can be altered according to your needs.

 function myFunction2() < if ($('#test').css('background-color') != '#198B07') < $('#test').css('background-color', '#198B07'); >else < $('#test').css('background-color', '#2A303C'); >return false; > 

The issue lies in the fact that when you use HTMLElement.style.background, you receive a string that showcases the color in RGB format. Once you assign the hexadecimal color ‘#198B07’ to the style property of the element, the value of ‘document.getElementById(«test»).style.background’ will become ‘rgb(25, 139, 7)’.

To enhance maintainability, it’s advisable not to directly style an element using JS. Instead, consider adding or removing a class and applying CSS styles to the element.

 function myFunction2() < if (document.getElementById("test").style.background !== '#198B07') < document.getElementById("test").style.background = '#198B07'; >else < document.getElementById("test").style.background = '#2A303C'; >return false; > 

Whats wrong with this JavaScript if/else statement?, So I’m learning JavaScript and I’m just playing around — bear with me here, I’m trying to learn some concepts so I’m hacking together a simple «Magic 8 …

Accordion if/else logic

It seems like my if/else logic is not accurate. At the beginning, the accordion pane in the accordion is only partially revealed to a height of 150px. When the user clicks on the header, it should fully open to 320px. After that, it should behave like the other accordion elements and smoothly hide/show. However, the current implementation is not seamless and the pane closes before it is completely revealed.

 

At a glance

What we do

How we do it

Where we reach

How

//generally slides all accordion elements with class "acc-content" when div with class "acc-header" is clicked $('.acc-header').click(function(e) < e.preventDefault(); $(this).toggleClass('acc-active'); $(this).next('.acc-content').slideToggle(200).siblings('.acc-content').slideUp(200); $(this).siblings().removeClass('acc-active'); >); //when the page loads 'peek' at the content of the first accordion content (to 150px depth) $('.slider').css('height','150px'); $('.slider').animate(< height: 'show'>, 'slow').addClass('itsopen'); //if its already been opened, close it, else open it to 320px $('.glanceH').click(function() < if(!$(this).hasClass('acc-active')) < $(this).next().siblings('.acc-content').slideUp(2000); $(this).siblings().removeClass('acc-active'); >else if($('.slider').hasClass('itsopen'))< $('.slider').animate(< height: 320>, 'slow'); > >); 

My apologies, I realized I didn’t fully read the question. As a result, I have provided a demonstration now.

//generally slides all accordion elements with class "acc-content" when div with class "acc-header" is clicked $('.accordion .acc-header').click(function() < var first = $('.slider'); // open peek if clicked, otherwise hide it if (first.is('.itsopen')) < if ($(this).next().is('.acc-active')) < // open peek to full height first.removeClass('itsopen').animate(< height: '320px' >, 'slow'); return; > else < // close first because a different header was clicked first.removeClass('itsopen acc-active').slideUp('slow'); >> // remove active class from all content $('.acc-content').removeClass('acc-active'); // show active content $(this).next().addClass('acc-active').toggle('slow'); // close all content that isn't active $('.acc-content:not(.acc-active').slideUp('slow'); return false; >) // initialize accordion with all content closed .next().hide(); //when the page loads 'peek' at the content of the first accordion content (to 150px depth) $('.slider') .css(< height: '0px' >) .show() .animate(< height: '150px' >, 'slow') .addClass('itsopen acc-active'); 

Javascript: How do I tweak my debounce function to, // Define debouncedFunk and toggle debouncedFunk = _.bind(debouncedFunk, <>, toggle); debouncedFunk = …

If statement toggle div else hide div broken

 click: function(event, data) < $('#clicked-state') .text('You clicked: '+data.name); if (data.name == "VA") < $('#va').toggle(); >else < $('#va').style.display = 'none'; >> >); 

The concept is to hide id VA when a state other than clicked, div is selected. Clicking ‘ VA ‘ toggles div VA , but div VA remains visible even when a different state is clicked. It must be hidden by clicking hide .

something.style.display = 'none'; 

. is the vanilla JavaScript way.

To utilize style.display in vanilla JS, you can access the first element of the jQuery object, as it is casted as a DOMElement.

$('something')[0].style.display = 'none'; // Cast to DOMElement rather than using a jQuery object 

Jquery — How to use innerHTML with JavaScript if/else, Else if, If user does not select skin tone from dropdown menu on click of SUBMIT button innerHTML message should say «Please select a skin tone.» …

Источник

Оцените статью