Reputation: 123
Need your help on this one. In navigation bar i have an item called author which shows info about author when clicked, in a form of dropdown. The problem is that dropdown is clickable and that makes it disappear. I want to be able to show/close it only in navigation bar.
<div id = 'Author' class = 'navbarItem'>Author
<div id = 'authorInfo'>
// info about author
</div>
const author = document.getElementById('Author');
const authorInfo = document.getElementById('authorInfo');
author.onclick = () => {
if(authorInfo.style.display == 'none' || authorInfo.style.display == '')
authorInfo.style.display = 'block'
else
authorInfo.style.display = 'none';
}
Have tried setting onclick event of authorInfo to null, that doesn't work.
Upvotes: 2
Views: 852
Reputation: 1757
Add the event parameter on listener to test if click was made on containter and not on its child. event.target
holds the clicked element.
const author = document.getElementById('Author');
const authorInfo = document.getElementById('authorInfo');
// You need the event parameter on function
author.onclick = function(event) {
// Do it only if clicked element is author div, not its child
if(event.target == author) {
if(authorInfo.style.display == 'none' || authorInfo.style.display == '')
authorInfo.style.display = 'block'
else
authorInfo.style.display = 'none';
}
}
<div id = 'Author' class = 'navbarItem'>Author
<div id = 'authorInfo' style="display:none;">
// info about author
</div>
</div>
Upvotes: 2