Reputation: 470
Consider the following HTML code snippet:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<nav>
<a href="" id="menu-icon"></a>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Work</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</body>
</html>
and the respective CSS code snippet (styles.css):
#menu-icon {
width: 40px;
height: 40px;
background-color: blue;
}
a#menu-icon:hover {background-color: black;}
#menu-icon {display:inline-block;}
nav ul {
display: none;
position: absolute;
padding: 20px;
border: 1px solid black;
right: 20px;
top: 60px;
width: 50%;
}
nav:hover ul {display: block;}
Basically, this is a simple navigation bar intended to work both for desktop and mobile. However, there is a problem when you use it in mobile: the menu disappear just after you touch the icon.
In order to solve this problem, it is necessary to change the line <a href="" id="menu-icon"></a>
to <a href="#" id="menu-icon"></a>
.
Issue
Is this behavior expected? Why? What is the reasoning for it?
Upvotes: 0
Views: 399
Reputation: 275
Like others have stated leaving a href
tag empty will actually still redirect the user to the root directory. This has been asked elsewhere and you can get a good reply here: Is an empty href valid?
Anytime you have an element on a page that you want to be clickable but you aren't actually going to be linking to anything, its best not to put it in an anchor tag. Instead you can do something like this:
<body>
<nav>
<span id="menu-icon"></span>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Work</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</body>
Then in your css you can make the span behave like a link by changing the cursor:
cursor: pointer;
This way your user will still know that this is an interactive element.
Upvotes: 1
Reputation: 3382
Provided that your current page is not the homepage (e.g., localhost:8888/foo.html
and not already localhost:8888/
), upon clicking/touching <a href="" id="menu-icon"></a>
, it'll redirect you back to the homepage (e.g., localhost:8888/
).
When you place a # <a href="#" id="menu-icon"></a>
, you'll notice that you'll not be redirected and simply add the # to the end of the URL (used for anchor links). Hence, your contents stays the same.
It's a misconception that href=""
will not redirect you, but it's actually equivalent to href="/"
. If you don't want it to redirect, you can simply remove the href
or just use another tag like <span>
.
Upvotes: 1