0

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;}

afuous
  • 1,478
  • 10
  • 12
Olchus
  • 11
  • 4

2 Answers2

1

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");
Nedim Hozić
  • 1,871
  • 15
  • 15
  • the problem is that the function does not work. I'm not sure but maybe that's happening because of reload? Is it possible? – Olchus May 16 '17 at 22:33
0

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>
Badacadabra
  • 8,043
  • 7
  • 28
  • 49
  • but... How "text" is not HTML? I don't need to hide div after typical page reload. I want to hide it when hyperlink on main page is clicked and I'm redirected to the other page. – Olchus May 16 '17 at 23:28