Javascript if/else not working as expected - javascript

I am trying to toggle a hidden menu with a link. But when i click on the link, it reopens the hidden menu instead of closing it.
Here is how i expect it to run:
When i click labelLink
if hiddenBox 's display = 'none', then change it to display = 'block'
if hiddenBox 's display = 'block', then delete its focus by blur() and set it display='none'
When i click outside of the hiddenBox when it has the focus, set hiddenBox 's display='none'
(This part is working well.)
JsFiddle
<ul>
<li>
<a id="labelLink" href="#"
onclick="
if(document.getElementById('hiddenBox').style.display === 'block'){
document.getElementById('labelLink').focus();
document.getElementById('hiddenBox').style.display ='none';
}
else{
document.getElementById('hiddenBox').style.display = 'block';
document.getElementById('hiddenBox').focus();
}
return false;"
>
Click Me
</a>
<div id="hiddenBox" tabindex="-1"
onblur="document.getElementById('hiddenBox').style.display ='none';"
>
I was hidden
</div>
</li>
</ul>

Do it this way instead.
var labelLink = document.getElementById('labelLink');
var hiddenBox = document.getElementById('hiddenBox');
labelLink.addEventListener('click', function() {
hiddenBox.style.display = hiddenBox.style.display == 'block' ? 'none': 'block';
});
labelLink.addEventListener('blur', function() {
hiddenBox.style.display = 'none';
})
#hiddenBox {
display: none
}
<ul>
<li><a id="labelLink" href="#">Click Me</a>
<div id="hiddenBox" tabindex="-1">I was hidden</div>
</li>
</ul>

As already pointed out, the two event listeners are interfering with each other. One way of fixing this is to remove the listener on labelLink when the hidden box is shown, and restore the listener with a slight pause after the hidden box is hidden again. JSFiddle
var labelLink = document.getElementById('labelLink'),
hiddenBox = document.getElementById('hiddenBox');
labelLink.addEventListener('click', showBox);
hiddenBox.addEventListener('blur', hideBox);
function showBox(){
hiddenBox.style.display = 'block';
hiddenBox.focus();
labelLink.removeEventListener('click', showBox);
}
function hideBox() {
hiddenBox.style.display = 'none';
labelLink.focus();
window.setTimeout(function() {
labelLink.addEventListener('click', showBox);
}, 500);
}
<a id="labelLink" href="#" >Click Me</a>
<div id="hiddenBox" tabindex="-1" style="display:none" >I was hidden</div>

Related

Making a dropdown menu using vanilla Javascript

I'm trying to figure out what is a good approach to accomplish a dropdown menu that opens when a user clicks on a div which functions as a button and hides when the user click again on it. The style in my CSS sheet is set as display: none. and this is as far as i've gone:
var xx = document.getElementById('dropdown-Container');
if (xx.display.style = 'none') {
xx.addEventListener('click', function showMenu() {
document.getElementById('dropdown-Container').style.display = 'block';
} else {
xx.style.display = 'none';
}, false);
}
<div type="button" id="dropdown-Container">
<a class="dropdown1" href="#">Link 1</a>
<a class="dropdown1" href="#">Link 2</a>
<a class="dropdown1" href="#">Link 3</a>
</div>
Search
</div>
The menu is hiding properly but when the user clicks on it, it's not opening up as I wish.
You need a double-equals in the 'none' comparison, at the very least.
You have made a mistake in the code by placing the if statement above the event listener. Use it like this.
var menu = document.getElementById('yourDropdownMenuIdHere');
var dropdown = document.getElementById('dropdown-Container');
menu.addEventListener('click', function showMenu(){
if( dropdown.style.display = 'none' ) {
dropdown.style.display = 'block';
} else {
dropdown.style.display = 'none';
}
});
Accessibility Issue: A div is not supposed to be used as a button for handling click. You can use a button tag instead

How to fix "Opened sidebar when page is loaded"?

I am making a sidebar nav. There is a hamburger button when clicked opens nav. But when page is loaded, it is already opened. I don't want it to already opened. How do I fix this?
I am a noob in JS. I have tried value 'javascript:void(0)' in href attribute, but it didn't work.
<a href="javascript:void(0)" class="click-menu" onclick="openMenu()">&9776;
</a>
<div class="side-menu" id="side-menu">
<a href="#" class="cross-btn" onclick="closeMenu()" style="font-size: 50px">×
</a>
Features
Pricing
Login
</div>
<script>
function openMenu() {
document.getElementById("side-menu").style.width = "250px";
}
function closeMenu() {
document.getElementById("side-menu").style.width = "0";
}
</script>
Expected result: Sidebar nav will open only when Hamburger icon is clicked.
Actual result: When page is loaded, nav is already opened.
Add display:none to the style of div #side-menu:
<div class="side-menu" id="side-menu" style="display:none;">
And instead of resizing the width of #side-menu, change the display to block when the menu is clicked, and back to none when the cross sign is clicked.
function openMenu() {
document.getElementById("side-menu").style.display = "block";
}
function closeMenu() {
document.getElementById("side-menu").style.display = "none";
}
The full code:
☰
<div class="side-menu" id="side-menu" style="display:none;">
×
Features
Pricing
Login
</div>
<script>
function openMenu() {
document.getElementById("side-menu").style.display = "block";
}
function closeMenu() {
document.getElementById("side-menu").style.display = "none";
}
</script>
P.S. Also change &9776; to ☰

Open one drop-down, close another with JavaScript

I am using this script to open a drop down menu and then close it when anything else but the trigger is clicked. Now I am trying to add a second drop down to another area on the page and repeat the script but it is breaking.
For instance, I click button A (Gravatar), and drop down A opens.
However when I add the second script and click button B (category) to open drop down B, down down A stays open.
Also adding the second script breaks the drop down close function of the first script.
Here is the script:
<script>
function openAccount(event) {
event.stopPropagation();
document.getElementById("gravatar").classList.toggle("open");
}
window.onclick = function(event) {
document.getElementById("gravatar").classList.remove("open");
}
</script>
<script>
function openCategory(event) {
event.stopPropagation();
document.getElementById("category").classList.toggle("open");
}
window.onclick = function(event) {
document.getElementById("gravatar").classList.remove("open");
}
</script>
<li class="gravatar">
<a href="#" class="dropbtn" onclick="openAccount(event)">
<img src="<?php echo $gravatar; ?>" alt="" />
<span class="fa fa-icon fa-caret-down"></span>
</a>
<ul class="dropdown" id="gravatar">
<li class="header">
<?php echo $user['email']; ?>
</li>
</ul>
</li>
<div class="category">
Properties<span class="fa fa-icon fa-caret-down"></span>
<div id="category">Test</div>
</div>
Goals:
Multiple drop down menus on different parts of the page.
On click opens drop down.
Click on anywhere else on the page closes the drop down.
On click also closes any previously opened menu.
I'd do something really simple like putting a data* attribute on the element that's clicked on that contains the ID of the element to show or hide, e.g.
// Toggle hidden class on/off
function toggleVis(event) {
// Stop click on element bubbling (to body)
event.stopPropagation();
// Get target element
var el = document.getElementById(this.dataset.id);
// If non-target elements are visible, hide them
hideAll(el);
// Toggle target
el.classList.toggle('hidden');
}
// Hide all, excluding passed element
function hideAll(el) {
Array.from(document.querySelectorAll('ul:not(.hidden)')).forEach(function(node){
if (el != node) node.classList.add('hidden');
});
}
// Attach listeners
window.onload = function() {
// Add to linkLike spans
Array.from(document.querySelectorAll('.linkLike')).forEach(function(node) {
node.addEventListener('click', toggleVis, false);
});
// Add hideAll listener to wndow
window.addEventListener('click', hideAll, false);
// Run hideAll
hideAll();
}
/* style span like link */
.linkLike {
text-decoration: underline;
cursor: pointer;
}
/* class to hide element */
.hidden {
visibility: hidden;
}
<ul id="a"><li>A</ul>
<ul id="b"><li>B</ul>
<ul id="c"><li>C</ul>
<ul id="d"><li>D</ul>
<div><span class="linkLike" data-id="a">Toggle A</span></div>
<div><span class="linkLike" data-id="b">Toggle B</span></div>
<div><span class="linkLike" data-id="c">Toggle C</span></div>
<div><span class="linkLike" data-id="d">Toggle D</span></div>
Of course there are other ways to do the association, but ID is simple, explicit and doesn't depend on document layout or formatting.

How do I highlight/un-highlight div if checkbox is clicked OR it's parent div is clicked?

Right now when I click on li, it is highlighted correctly. However, when I click on the checkbox itself, there is no response. How do I highlight/un-highlight the li when clicking on either the li or the checkbox itself?
I also do not wish to adjust this part of my jQuery: $('.rightP').find('ul').on( (because the elements inside the ul are generated dynamically) if possible.
HTML
<div class = "rightP">
<ul>
<li>
<div class="sender">
<span>
<input type="checkbox">
</span>
</div>
<div id=2 class="message">
<p>test</p>
</div>
...
</li>
...
</ul>
...
</div>
JQuery :
deleteIDs = [];
$('.rightP').find('ul').on("click","li",function(event) {
var checkbox = $(this).find("input[type='checkbox']");
if(checkbox.hasClass('open')){
if(!checkbox.prop("checked") ){
checkbox.prop("checked",true);
$(this).css({'background-color':"#EEEEEE"});
$(this).find('div.message').each(function(){
deleteIDs.push($(this).prop('id'));
});
} else {
checkbox.prop("checked",false);
$(this).css({'background-color':"white"});
$(this).find('div.message').each(function(){
var deleteID = $(this).prop('id');
deleteIDs = $.grep(deleteIDs,function(value){
return (value!=deleteID);
});
});
}
}
});
I think if you want handle li click. You must not use check checkbox. You image and change it src to click.png when click and noclick.png when no click. Hope this help!
Ok if you dont want image i mention you my full code no use image, it work ok
<!DOCTYPE html >
<html >
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<div class = "rightP">
<ul>
<li>
<div class="sender">
<span>
<input type="checkbox">
</span>
</div>
<div id=2 class="message">
<p>test</p>
</div>
</li>
</ul>
<script>
deleteIDs = [];
var isnotcheck=true;
var clickcheckbox=false;
$('.rightP').find('ul').on("click","input",function(event) {
clickcheckbox=true;
isnotcheck=!isnotcheck;
});
$('.rightP').find('ul').on("click","li",function(event) {
;
if(!clickcheckbox)
{
isnotcheck=!isnotcheck;
}
var checkbox = $(this).find("input[type='checkbox']");
clickcheckbox=false;
if(!isnotcheck ){
checkbox.prop("checked",true);
$(this).css({'background-color':"#EEEEEE"});
$(this).find('div.message').each(function(){
deleteIDs.push($(this).prop('id'));
});
} else {
//alert(checkbox);
checkbox.prop("checked",false);
$(this).css({'background-color':"white"});
$(this).find('div.message').each(function(){
var deleteID = $(this).prop('id');
deleteIDs = $.grep(deleteIDs,function(value){
return (value!=deleteID);
});
});
}
});
</script>
</div>
</body>
</html>
You look two event. li click and checkbox click , two event occured if you click on checkbox if no one event occured. You can see my variable
var isnotcheck=true;
var clickcheckbox=false;
to know click or not click checkbox.
Hope this help!
Rather than this line
$('.rightP').find('ul').on("click","li",function(event) {
You can try
$('.rightP').on("click","ul li",function(event) {
When you're dealing with generated content you should use deferred event handlers, here's an example using Jquery UI to apply the highlight effect when you click either the checkbox or div.
http://jsbin.com/kibicega/1/

Changing the state of a button HTML

I have this code in the body of my HTML which acts as a show/hide button and it is styled via CSS. However I only have the option to title the button once i.e 'Read more.." but after the button has been selected I would like it to change to 'Read less'. Here is the code I am using:
<button title="Click to show/hide content" type="button"
onclick="if(document.getElementById('spoiler') .style.display=='none')
{document.getElementById('spoiler')
.style.display=''}else{document.getElementById('spoiler')
.style.display='none'}">Read more...
</button>
Any help would be greatly appreciated, thanks in advance.
Try:
HTML:
<button title="Click to show/hide content" type="button" onclick="func()" id="but">Read more...</button>
<div id="spoiler" style="display:none">TEXT TEXT TEXT</div>
JS:
function func(){
if(document.getElementById('spoiler') .style.display=="none"){
document.getElementById('spoiler').style.display="block";
document.getElementById('but').innerHTML="Read less...";
}
else{
document.getElementById('spoiler').style.display='none';
document.getElementById('but').innerHTML="Read more...";
}
}
DEMO
Firstly, get out of the habit of bundling JavaScript inline as HTML attributes. Look into DOM-scripting centrally from your JS scripts rather than in your HTML.
The essence of what you need to do is to query something each time the button is clicked, and act accordingly. The visibility of the spoiler area, for example.
(Note, you will need to give your button an ID, e.g. mybutton, for this:)
document.querySelector('#mybutton').addEventListener('click', function() {
var
spoiler = document.querySelector('#spoiler'),
showing = spoiler.style.display != 'none';
spoiler.style.display = showing ? 'none' : 'block';
this.textContent = 'Read '+(showing ? 'more' : 'less');
}, false);
So on click, we interrogate the display style of #spoiler. If it's showing, we hide it, and if it's hidden, we show it, updating the button text accordingly.
HTML:
<button id="btn" title="Click to show/hide content" type="button" onclick="readmore()">Read More...</button>
<div id="spoiler" style="display:none">spoiler text</div>
JS:
function readmore(){
var btn = document.getElementById('btn');
var spoiler = document.getElementById('spoiler');
if(spoiler.style.display=='none') {
spoiler.style.display = '';
btn.innerHTML = "Read Less ...";
} else {
spoiler.style.display = 'none';
btn.innerHTML = "Read More ...";
}
}
Here is a DEMO at jsFiddle.

Categories

Resources