Content switching with Javascript - javascript

I have 3 sections of specific interest on my home page.
What I'd like to do is set up links that call a javascript function that makes sure 2 sections are hidden and ONLY the section whose button was clicked is displayed.
Here's my code:
<div id="idc" class="leftFloat"><span id="title" class="title1">Introduction</span></div>
<div class="rightFloat">
<div id="agri"><a onclick="ContentSwitch('Agri');">Agri Industries</a></div>
<div id="ict"><a onclick="ContentSwitch('ict');">ICT Investments</a></div>
<div id="intro"><a onclick="ContentSwitch('intro');">Introduction</a></div>
</div>
<div id="agriContent" style="display: none;">
<div class="vrtlay_both">AGRI INDUSTRIES</div>
</div>
<div id="ictContent" style="display: none;">
<div class="vrtlay_both">ICT INVESTMENTS</div>
</div>
<div id="introContent">
<div class="vrtlay_both">ICT INVESTMENTS</div>
</div>
<script type="text/javascript">
function ContentSwitch(id) {
if (id = "Agri") {
if (document.getElementById("agriContent").style.display = "none") {
document.getElementById("agriContent").style.display = "block";
// Hide other content
document.getElementById("ictContent").style.display = "none";
document.getElementById("introContent").style.display = "none";
// Change the look of the title
document.getElementById("idc").style.backgroundColor = "rgb(0, 100, 0)";
document.getElementById("idc").style.color = "rgb(255, 255, 255)";
document.getElementById("title").innerHTML = "Agri Industries";
} else {
return;
}
}
if (id = "ict") {
if (document.getElementById("ictContent").style.display = "none") {
document.getElementById("ictContent").style.display = "block";
// Hide other content
document.getElementById("agriContent").style.display = "none";
document.getElementById("introContent").style.display = "none";
// Change the look of the title
document.getElementById("idc").style.backgroundColor = "rgb(36, 46, 111)";
document.getElementById("idc").style.color = "rgb(255, 255, 255)";
document.getElementById("title").innerHTML = "ICT Investments";
} else {
return;
}
}
if (id = "intro") {
if (document.getElementById("introContent").style.display = "none") {
document.getElementById("introContent").style.display = "block";
// Hide other content
document.getElementById("agriContent").style.display = "none";
document.getElementById("ictContent").style.display = "none";
// Change the look of the title
document.getElementById("idc").style.backgroundColor = "rgb(255, 255, 255)";
document.getElementById("idc").style.color = "rgb(0, 0, 0)";
document.getElementById("title").innerHTML = "Introduction";
} else {
return;
}
}
}
</script>
The javascript isn't firing.
I'm aware that this isn't the most elegant (or necessarily efficient) way of doing this, so if anyone can suggest a better way, I'm all ears.
Right now though, I'd just really like for this to work, but I can't see the problem.

Comparisons in Javascript use the double equals operator (==), not a single equals, so you're assigning the values in your if statements. Try changing them and see if it works.

<deep breath>
Ok...
if (id = "Agri") {
Well there's your actual problem. You're making an assignment = not a comparison ==.
Now to improve the code.
"id" is exclusive and a constant expression so you should arguably use a switch here, but you should at least be using elseif.
if (document.getElementById("agriContent").style.display = "none") {
Again, wrong operation here, but you're also failing to capture a reference to the element you're intertested in so you're losing performance when you run getElementById over and over again. Further, you're testing for a particular style property so you're tightly coupled to an implementation. This makes your code much less flexible and much more error prone. CSS classes are your friends: use them, change their application, leave style alone.
} else {
return;
}
Else do nothing? You're doing this to compensate for the lack of elseif statements in previous logic - this block is just confusing.

I'd suggest using CSS classes and jQuery to do this.
Instead of passing in a string value do something like this:
<div id="agri"><a onclick="ContentSwitch($("#agriContent"));">Agri Industries</a></div>
<div id="ict"><a onclick="ContentSwitch($("#ictContent"));">ICT Investments</a></div>
<div id="intro"><a onclick="ContentSwitch($("#introContent"));">Introduction</a></div>
In your content panels, do this:
<div id="agriContent" class="invisible">
<div class="vrtlay_both">AGRI INDUSTRIES</div>
</div>
<div id="ictContent" class="invisible">
<div class="vrtlay_both">ICT INVESTMENTS</div>
</div>
<div id="introContent" class="visible">
<div class="vrtlay_both">ICT INVESTMENTS</div>
</div>
Then, in ContentSwitch, do something like this:
function ContentSwitch(div) {
$(".visible").addClass("invisible").removeClass("visible");
div.removeClass("invisible").addClass("visible");
}
Might not be perfect, but the best I can come up with off the top of my head.

This is just a suggestion but you could refactor your code a bit.
var agriContent, ictContent, introContent, idc, title;
function ContentSwitch(id) {
agriContent = agriContent || document.getElementById("agriContent");
ictContent = ictContent || document.getElementById("ictContent");
introContent = introContent || document.getElementById("introContent");
idc = idc || document.getElementById("idc");
title = title || document.getElementById("title");
switch (id) {
case "Agri":
if (agriContent.style.display !== "none") {
return;
}
agriContent.style.display = "block";
ictContent.style.display = "none";
introContent.style.display = "none";
idc.style.backgroundColor = "rgb(0, 100, 0)";
idc.style.color = "rgb(255, 255, 255)";
title.innerHTML = "Agri Industries";
break;
case "ict":
// ...
break;
case "intro":
// ...
break;
}
}

Related

Unable to hide div using js, but I'm able to show div with js. Seems like "else if" isn't working. Could someone look over this?

I have a div that I can show with js, but I can't seem to close. Using if .... else if...
For example:
<a id="downgrade" onclick="showDowngradeDiv()" href="javascript:void(0)"><h1>Downgrade ▼</h1></a>
<div id="downgrade-text">
<h2>text</h2>
<p>A paragraph of text</p>
</div>
function showDowngradeDiv() {
const DowngradeDiv = document.getElementById("downgrade-text");
if (DowngradeDiv.style.display = "none") {
DowngradeDiv.style.display = "block";
}
else if (DowngradeDiv.style.display = "block") {
DowngradeDiv.style.display = "none";
alert("test");
}
}
#downgrade-text {
display: none;
}
If anyone has any idea, let me know because I don't know what I'm doing wrong here right now.
You are assigning the display property at the if/else. Please use the double equal sign operator.
if (DowngradeDiv.style.display = "none")
if (DowngradeDiv.style.display == "none")
Funnily enough, just messed around with js and ended up doing this and somehow it's working?
function showDowngradeDiv() {
const DowngradeDiv = document.getElementById("downgrade-text");
if (DowngradeDiv.style.display == "block") {
DowngradeDiv.style.display = "none";
}
else {
DowngradeDiv.style.display = "block";
DowngradeDiv.scrollIntoView({behavior: "smooth"});
}
}
but if I were to switch the statements around and say if Downgrade.style.display == "none" then change it to block and scroll to it else set display to none. That wouldn't work for some reason, but flipping it seems to have gotten me what I wanted functionally.

Change the color of a div back and forth on click

I'm working on a homework assignment to change the color of this this div back and forth on click
<div id = "color-block">
<p id="center-text">The color is: <span id = "color-name">#F08080</span> </p>
</div>
So far I have this, which changes the color once, but then will not change it back to the original color
document.getElementById("color-block").onclick = function () {
changeColor();
};
function changeColor() {
if (
(document.getElementById("color-block").style.backgroundColor = "#f08080")
) {
document.getElementById("color-block").style.backgroundColor = "#008080";
} else {
document.getElementById("color-block").style.backgroundColor = "#f08080";
}
}
I'm unsure of what is causing the else statement to not work. Can anyone point me in the right direction?
For some reason (I'm not sure why) HEX colors (e.g. #ff0000) get converted to RGB colors (e.g. rgb(255,0,0)). It's therefore easier to just use RGB colors. There was also a fault in your if. You have to use a == for comparisons. You code ends up being like this:
document.getElementById("color-block").onclick = function () {
changeColor();
};
function changeColor() {
if (
(document.getElementById("color-block").style.backgroundColor == "rgb(240, 128, 128)")
) {
document.getElementById("color-block").style.backgroundColor = "rgb(0, 128, 128)";
} else {
document.getElementById("color-block").style.backgroundColor = "rgb(240, 128, 128)";
}
}
Demo: https://jsfiddle.net/d174aj95/

Javascript : why i have to click 2 times to run the function?

window.onload = function(){
var about2 = document.getElementById("about");
about2.addEventListener("click",about);
}
function about(){
var divabout = document.getElementById("aboutme");
if(divabout.style.display == "none"){
divabout.style.display = "flex";
divabout.style.justifyContent ="center";
}else{
divabout.style.display ="none";
}
}
please tell me the reason why i have to click twice to run this function .And how to fix pls . many thanks .
i just set display:none for 1 div tag in css , and i want to change display attributes .
Because you haven't set any dislplay property to your HTML by default.
That's why On first click javascript sets everything it needs. then started working from 2nd click.
Here is your code, where you dind't add style in html
<div id="about">Hello</div>
<div id="aboutme">About Me</div>
And Here if I fix/add this style="display:flex;justify-content: center;" in your about me like this
<div id="about">Hello</div>
<div id="aboutme" style="display:flex;justify-content: center;">About Me</div>
Now you can check you need only one click to run
window.onload = function() {
var about2 = document.getElementById("about");
about2.addEventListener("click", about);
}
function about() {
var divabout = document.getElementById("aboutme");
if (divabout.style.display == "none") {
divabout.style.display = "flex";
divabout.style.justifyContent = "center";
} else {
divabout.style.display = "none";
}
}
<div id="about">Hello</div>
<div id="aboutme" style="display:flex;justify-content: center;">OK About Me</div>

JavaScript addEventListener 'click''

I struggling with very basic thing
I am trying to make this side-nav appear and disappear with JavaScript. The code below only activates the nav bar but doesn't deactivate it. Tried all options but I don't know how to call function to close nav-bar.
Thank you
HTML
<div id="mySidenav" class="sidenav">
×
About
Services
Clients
Contact
</div>
<!-- Use any element to open the sidenav -->
<span id="MyElement">×</span>
JS
<script type="text/javascript">
function changeClass() {
document.getElementById("mySidenav").style.width = "250px";
}
window.onload = function() {
document.getElementById("MyElement").addEventListener('click',changeClass);
}
</script>
</body>
</html>
You can't have to objects with the same ID (use name instead?)
You have a typo in else if with comparator mark and another in the next line with assingment mark.
Since in menu.style.width == "-250px" you would be assigning value to -250 (menu.style.width == "0px) would never pass and it would keep assigning value -250 whenever someone clicks the button, but that fails, because you have a typo in your assingment mark.
Width cannot be negative
Is let compatable with your browser?
Have you considered using display:none and display:block (or whatever display you have)?
function toggleMenu() {
var menu = document.getElementById('mySidenav');
if (menu.style.display == "none")
menu.style.display = "inline-block"; //block
else
menu.style.display = "none";
}
window.onload = function() {
document.getElementById("MyElement").onclick = toggleMenu;
}
your else statement section seems to have the comparator (==) and assignment (=) the wrong way around :
} else if (menu.style.width = "250px") {
menu.style.width == "-250px";
}
looks like it should be
} else if (menu.style.width == "250px") {
//setting a negative width will immediately break the toggle logic.
//just set it to 0px.
menu.style.width = "0px";
}
Full example :
function changeClass() {
var sidenavElement = document.getElementById("mySidenav");
if(sidenavElement.style.width == "0px")
{
sidenavElement.style.width = "250px";
}
else
{
sidenavElement.style.width = "0px";
}
}
window.onload = function() {
document.getElementById("MyElement").addEventListener('click',changeClass);
}
#mySidenav
{
overflow:hidden;
height:100px;
background:green;
}
<div id="mySidenav" style="width:0px">
HELLO I AM SIDENAV
</div>
<button id="MyElement">toggle it</button>
There is many problem in your code, you have 2 elements inside your DOM with same ID as mentioned by Marek Maszay.
Your else statement should use == in condition and = for assignation.
Last thing, you should not use width property to display or not an element there is a display property in css
<html>
<body>
<div id="mySidenav" class="sidenav">
<span class="closebtn" id="MyElement">×</span>
<span id="menu">
About
Services
Clients
Contact
</span>
</div>
<!-- Use any element to open the sidenav -->
<span id="MyElement2">×</span>
<script type="text/javascript">
function toggleMenu() {
let menu = document.getElementById('menu');
if (menu.style.display == "") {
menu.style.display = "none";
} else if (menu.style.display == "none") {
menu.style.display = "";
}
}
window.onload = function() {
document.getElementById("MyElement").addEventListener('click',toggleMenu);
}
</script>
...
</body>
</html>
When display value is "", it take the default display value of an element, when its value is none the element is not displayed.
Here is your code modified.
EDIT
For some reason changing width to 0px doesn't hide the element. Element change from line to column, it seem that the browser try to fill element with content and put at least one word per line.
Seem like other people on web are having same problem.

JavaScript "example" of a switch to compare HTML button id's

I posted a question a week ago about how to use JavaScript switch statement to compare this.id. I found it hard to get my function/object methods out of the switch as variables. Using strict mode and trying to do this seems impossible. However I did find one way to get the results I wanted.
"use strict"
function fragmentLoader() {
getID(this.id);
}
function getID(x) {
var theID = x;
switch (theID) {
case "myFirstID":
myDate();
break;
case "mySecondID":
changeStyle();
break;
case "myThirdID":
myText();
break;
default:
otpt = "ERROR!";
}
}
function myDate() {
document.getElementById('content').innerHTML = Date();
}
function changeStyle() {
var whatColor = document.getElementById("content").style.color;
if ( whatColor === "black") {
document.getElementById("content").style.color = "blue";
} else {
document.getElementById("content").style.color = "black";
}
}
function myText() {
document.getElementById('content').innerHTML = "This Text will display";
}
document.getElementById("content").style.color = "black";
document.querySelector('#myFirstID').addEventListener('click', fragmentLoader);
document.querySelector('#mySecondID').addEventListener('click', fragmentLoader);
document.querySelector('#myThirdID').addEventListener('click', fragmentLoader);
<div>
<div>
<button id="myFirstID">
Press for Date and Time.
</button>
</div>
<div>
<button id="mySecondID">
Press to change style color.
</button>
</div>
<div>
<button id="myThirdID">
Press for Text.
</button>
</div>
<p id="content">content here
</p>
</div>
Had to laugh at my example because for some odd reason it takes 2 clicks to get the style to change. Any ideas as to why? NOTE : " This is now FIXED"
Other than that I hope this helps someone else.
-Rob
This line is the reason your code does not work as expected:
document.getElementById("content").style.color === "black";
You're trying to initially set the color to black, but you used to many "=" signs. Change that line to:
document.getElementById("content").style.color = "black";
... and your code will work!

Categories