0

I am using onclick method on a link in order to display a div. However, the div disappears after displaying for a second.

function view() {
  document.getElementById('topmenu').setAttribute('style', 'display:block');
}
#topbar {
  background-color: yellow;
  overflow: auto;
}

#topmenu {
  display: none;
}
<header>
  <div id="topbar">
    <img src="/images/santorini-wedding-photographer-logo.png" style="float: left;">
    <span style="float: right;"><a href="" onclick="view()">MENU</a></span>
  </div>
  <div id="topmenu">
    some text here
  </div>
</header>
j08691
  • 204,283
  • 31
  • 260
  • 272
Grey-lover
  • 635
  • 3
  • 7
  • 21

2 Answers2

2

Your anchor tag has a href attribute, which is following the link and changing the page contents. Remove the HREF ( which is actually a bad idea ), or better yet; use a span or something instead.

FYI: There are also multiple other solutions available to keep the href, but prevent the page from changing location.

function view() {
   document.getElementById('topmenu').setAttribute('style', 'display:block');
}
#topbar {
 background-color: yellow;
 overflow: auto;
}
#topmenu {
 display:none;
}
<header>
  <div id="topbar">
   <img src="<?php bloginfo('stylesheet_directory'); ?>/images/santorini-wedding-photographer-logo.png" style="float: left;">
   <span style="float: right;"><a onclick="view()">MENU</a></span>
  </div>
  <div id="topmenu">
   some text here
  </div>
 </header>
Steven Stark
  • 1,249
  • 11
  • 19
0

In your anchor tag, set your href to href="#!" so that the event doesn't propagate. And your code for the div to show works as expected.

It would also work with href="#", but this would take you back to the top of the page in case you're somewhere at the bottom.

  • on interesting, I have never seen the `#!` approach before. do you have a link that describes how this works? – Steven Stark Mar 29 '19 at 17:59
  • 1
    You can try these links. It should give a little idea about how it works. [Link-1](https://stackoverflow.com/questions/41394896/what-if-i-use-instead-of-in-href-of-anchor-tag-a) [Link-2](https://stackoverflow.com/questions/4855168/what-is-href-and-why-is-it-used/21397285) – Rahul Viswanath Mar 29 '19 at 18:02