Sandwich stack between Javascript If/Else?

Can someone give me some idea about the best way of sandwiching a stack in a Javascript if/else statement?

I want to display a stack only if a condition is met, which relies on Javascript… If the condition isn’t met, I want to display a different stack…

Any ideas please?

Unlike PHP, I cannot think of a safe and reliable way of splitting <script> tags to insert HTML content or stacks. Particularly from an aspect of un-escaped quote marks in your code.

Have you tried toggling class names like this?

function myScript() {

	var weather;
	var stacks_to_display = document.getElementsByClassName('myStack');

	if (weather == "sunny") {
	    stacks_to_display.classList.toggle("sunny");
	} else { 		
        stacks_to_display.classList.toggle("overcast"); 	
    }
}

Depending on the condition returned, you can add or remove class names, using toggle, add or remove methods:

https://www.w3schools.com/howto/howto_js_toggle_class.asp
https://www.w3schools.com/howto/howto_js_add_class.asp
https://www.w3schools.com/howto/howto_js_remove_class.asp

Then you can write CSS code to control which are shown, and which are hidden:

.myStack.overcast {
    display: none;
}

Of course, the content for these stacks would always be visible in the page source code. This method only changes their visibility on the screen.

If you needed to physically remove all the code and content from the page, then server-side PHP is the way to go. And PHP would let you nest stacks properly within the “if” statements without too much difficulty.

-Will.

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.