Reputation: 11
I want to use vanilla js in my project. I have some functions, and I have problem with one of them. The idea of script is: click link on main page, which redirects to other page; add class to #div1. When I click a link and I'm redirecting to other page - nothing hepens. I can't find I do wrong.
HTML from main page:
<a href="pagelink" id="view">text</a>
HTML from other page:
<div class="row" id="div1"></div>
<div class="row" id="div2"></div>
JS
window.onload = function () {
var hideDivOne = document.getElementById("div1"),
View = document.getElementById("view");
function swap() {
hideDivOne.className += " notdisplayed";
}
if(View){
View.addEventListener("click", swap, false);
}
}
CSS
.notdisplayed {display:none;}
Upvotes: 0
Views: 66
Reputation: 8497
Your code does not make sense... On the other page, View
is null
because your link is not in the HTML anymore! Therefore, nothing is executed, which is not what you want.
In fact, you do not need JS in your main page. Just use the native behavior of the HTML link by putting the right URL in the href
attribute: <a href="other_page.html" id="view">text</a>
When you are on the other page, you can hide the div using the style
property. Look at this demo:
.row {
width: 100px;
height: 100px;
}
#div1 {
background-color: red;
}
#div2 {
background-color: blue;
}
<div class="row" id="div1"></div>
<div class="row" id="div2"></div>
window.onload = function () {
document.getElementById("div1").style.display = 'none';
};
.row {
width: 100px;
height: 100px;
}
#div1 {
background-color: red;
}
#div2 {
background-color: blue;
}
<div class="row" id="div1"></div>
<div class="row" id="div2"></div>
Upvotes: 0
Reputation: 1901
Instead of
hideDivOne.className += " notdisplayed";
try with:
hideDivOne.classList.add("notdisplayed");
and if you want to remove this class:
hideDivOne.classList.remove("notdisplayed");
or toggle class:
hideDivOne.classList.toggle("notdisplayed");
Upvotes: 1