Javascript if else function working only after first click - javascript

I've checked other questions about the same effect but the ones I found haven't helped.
The javascript code works perfectly but not on first click. (When clicked the first time nothing happens but every next time all is well.) It is placed at the end of HTML's <head> as
<script>
$(function () {
$("#askLink").click(function () {
if (document.getElementById('askArticle').style.display === "none") {
document.getElementById('askArticle').style.display = "block";
document.getElementById('CONTENT').style.display = "none";
}
else {
document.getElementById('askArticle').style.display = "none";
document.getElementById('CONTENT').style.display = "block";
}
});
});
</script>
And the askLink is set up as
<li>
Ask
</li>
Another hyperlink is set up pretty much the same way with a different function and isn't affected by such an issue.
What am I missing?

Remove the javascript from a href:
Ask
Should be this:
Ask
Or, you may use '':
Ask
Also, try to use preventDefault():
$("#askLink").click(function (e) {
e.preventdefault();

since you are using jQuery, you could simply do:
$(function () {
$("#askLink").click(function () {
var askArticle = $('#askArticle');
//check if #askArticle is visible
var isShown = askArticle.is(":visible");
askArticle.toggle(!isShown); //set to show or hide as per isShown
$('#CONTENT').toggle(isShown);
});
});
and btw, your link Ask will work without any change to it

Replace the 'javascript:;' from the anchor to '#'
Ask
And to prevent the page to be refreshed or go at the top use preventDefault() as such:
$("#askLink").click(function(e) {
e.preventDefault();
if(document.getElementById('askArticle').style.display === "none"){
document.getElementById('askArticle').style.display = "block";
document.getElementById('CONTENT').style.display = "none";
}
else{
document.getElementById('askArticle').style.display = "none";
document.getElementById('CONTENT').style.display = "block"; //Its block not "CD"
}
});

You should use on not click:
<script>
$(function () {
$("#askLink").on("click" , function (e) {
e.preventDefault();
if (document.getElementById('askArticle').style.display === "none") {
document.getElementById('askArticle').style.display = "block";
document.getElementById('CONTENT').style.display = "none";
}
else {
document.getElementById('askArticle').style.display = "none";
document.getElementById('CONTENT').style.display = "block";
}
});
});
</script>

Related

div needs to be clicked twice to trigger event listener js

When I click on the .current-pet-icon div, I need to click it twice before it shows my menu. but every subsequent click after is okay. Just when I refresh / load the page the first time I need to double click. Any help wpuld be greatly appreciated!
Javascript
const menuToggle = document.querySelector('.current-pet-icon')
const openedNav = document.querySelector('.nav-popout');
const shadowNav = document.querySelector('.shadow-nav');
menuToggle.addEventListener('click', () => {
if (openedNav.style.display === "none") {
openedNav.style.display = "block";
shadowNav.style.display = "block";
} else {
openedNav.style.display = "none";
shadowNav.style.display = "none";
}
});
shadowNav.addEventListener('click', () => {
if (openedNav.style.display = "block") {
openedNav.style.display = "none";
shadowNav.style.display = "none";
}
});
HTML
<div class="pet-icon-container">
<img class="current-pet-icon" src="https://www.burgesspetcare.com/wp-content/uploads/2021/08/Hamster.jpg" alt="current pet icon">
</div>
Assuming that there is a CSS style assigned to hide both .nav-popout and .shadow-nav elements initially then a modified version of the original js code appears to function as expected.
const menuToggle = document.querySelector('.current-pet-icon')
const openedNav = document.querySelector('.nav-popout');
const shadowNav = document.querySelector('.shadow-nav');
menuToggle.addEventListener('click', (e)=>{
openedNav.style.display = openedNav.style.display == 'block' ? 'none' : 'block';
shadowNav.style.display = shadowNav.style.display == 'block' ? 'none' : 'block';
});
shadowNav.addEventListener('click', (e)=>{
if( openedNav.style.display == "block" ) {
shadowNav.style.display = openedNav.style.display = "none";
}
});
.pet-icon-container img{
width:150px;
}
.nav-popout,
.shadow-nav{
display:none;
}
<div class="pet-icon-container">
<img class="current-pet-icon" src="https://www.burgesspetcare.com/wp-content/uploads/2021/08/Hamster.jpg" alt="current pet icon" />
</div>
<div class='nav-popout'>#NAV-POPOUT#</div>
<div class='shadow-nav'>#SHADOW-NAV#</div>
A quick console.log(openedNav.style.display) will help you find the issue. In the first call to the click handler, openNav.style.disply is actually empty (not 'none').
Why does this happen
If you access a DOM Element via getElementById, you'll not be able to read the computed style of that element, because it is defined inside the CSS file (I assume you are doing that).
How to fix it
use getComputedStyle. Or see the top answers to these questions if you wanna know more:
document.getElementById(...).style.display is blank
myDiv.style.display returns blank when set in master stylesheet
menuToggle.addEventListener("click", () => {
if (getComputedStyle(openedNav).display=== "none") {
openedNav.style.display = "block";
shadowNav.style.display = "block";
} else {
openedNav.style.display = "none";
shadowNav.style.display = "none";
}
});

how to replace vanilla JS "click to show/hide" action with jQuery by changing CSS property

I'm following this tutorial: https://www.w3schools.com/jquery/jquery_css.asp for a homework question.
The vanilla JS to be replaced with jQuery looks like:
document.getElementById('menu-signin').addEventListener('click', function() {
document.getElementById('blanket').style.display = 'block';
document.getElementById('signin-box').style.display = 'block';
});
document.getElementById('menu-join').addEventListener('click', function() {
document.getElementById('blanket').style.display = 'block';
document.getElementById('join-box').style.display = 'block';
});
document.getElementById('blanket').addEventListener('click', function() {
document.getElementById('blanket').style.display = 'none';
document.getElementById('signin-box').style.display = 'none';
document.getElementById('join-box').style.display = 'none';
});
document.getElementById('cancel-signin-button').addEventListener('click', function() {
document.getElementById('blanket').style.display = 'none';
document.getElementById('signin-box').style.display = 'none';
document.getElementById('join-box').style.display = 'none';
});
document.getElementById('cancel-join-button').addEventListener('click', function() {
document.getElementById('blanket').style.display = 'none';
document.getElementById('signin-box').style.display = 'none';
document.getElementById('join-box').style.display = 'none';
});
I tried including the CDN which did not work so downloaded jQuery non-minified version into folder js and put this in the <head></head>:
<script src="js/jquery-3.5.1.js"></script>
My jQuery to replace the above vanilla JS is:
<script>
//show signin on click
$(document).ready(function()){
$("#menu-signin").click(function()){
$("#blanket").css("display", "block")
$("#signin-box").css("display", "block")
}
}
$(document).ready(function()){
$("#menu-join").click(function()){
$("#blanket").css("display", "block")
$("#join-box").css("display", "block")
}
}
//hide blanket on click
$(document).ready(function()){
$("#blanket").click(function()){
$("#blanket").css("display", "none")
$("#signin-box").css("display", "none")
$("#join-box").css("display", "none")
}
}
//hide on cancel
//hide blanket on click cancel
$(document).ready(function()){
$("#cancel-signin-button").click(function()){
$("#blanket").css("display", "none")
$("#signin-box").css("display", "none")
$("#join-box").css("display", "none")
}
}
//hide blanket on click cancel
$(document).ready(function()){
$("#cancel-join-button").click(function()){
$("#blanket").css("display", "none")
$("#signin-box").css("display", "none")
$("#join-box").css("display", "none")
}
}
</script>
It will not show the blanket and modals for sign in nor join.
I'm guessing you haven't looked at your console for errors.
You don't need to include ready around everything, its just needed to wrap once.
However, the actual error that you will see is you are missing the end ) for the clicks, and for the ready. Instead that ) was added after function instead of after the end }.
I also updated your function to include the jquery functions for hide/show.
$(document).ready(function(){
$("#menu-signin").click(function(){
$("#blanket").show()
$("#signin-box").show()
});
$("#menu-join").click(function(){
$("#blanket").show()
$("#join-box").show()
});
$("#blanket").click(function(){
$("#blanket").hide()
$("#signin-box").hide()
$("#join-box").hide()
});
$("#cancel-signin-button").click(function(){
$("#blanket").hide()
$("#signin-box").hide()
$("#join-box").hide()
});
$("#cancel-join-button").click(function(){
$("#blanket").hide()
$("#signin-box").hide()
$("#join-box").hide()
});
});

Disable burger menu while the user is inside another menu option

I just need to disable my burger menu while the user is inside another menu option. Unfortunately nothing can disable it as the menu is always active.
PS: the functions disableLink() and ableLink() dont work, everything else works fine.
document.querySelector('.hamburger-menu').addEventListener('click', () => {
document.querySelector('.nav-wrapper').classList.toggle('change');
var x = document.getElementById("top-nav-id");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
document.querySelector('#home-menu').addEventListener('click', () => {
document.getElementById("class-nav-1").style.display = "block";
disableLink();
});
document.querySelector('#close-window').addEventListener('click', () => {
document.getElementById("class-nav-1").style.display = "none";
ableLink();
});
});
function disableLink() {
document.getElementById('nav-wrapper').disabled=true;
document.getElementById('nav-wrapper').removeAttribute('href');
document.getElementById('nav-wrapper').style.textDecoration = 'none';
document.getElementById('nav-wrapper').style.cursor = 'default';
document.getElementById('nav-wrapper').style.visibility = hidden;
document.getElementById('nav-wrapper').style['pointer-events'] = 'none';
document.getElementById('hamburger-menu').disabled=true;
document.getElementById('hamburger-menu').removeAttribute('href');
document.getElementById('hamburger-menu').style.textDecoration = 'none';
document.getElementById('hamburger-menu').style.cursor = 'default';
document.getElementById('hamburger-menu').style.visibility = hidden;
document.getElementById('hamburger-menu').style['pointer-events'] = 'none';
}
function ableLink() {
document.getElementById('change').disabled=false;
document.getElementById('change').addAttribute('href');
document.getElementById('change').style.textDecoration = 'solid'
document.getElementById('change').style.cursor = 'pointer';
}
In the click event listener, I can see the 'nav-wrapper', 'hamburger-menu' and 'change' are classes not ids. So rather than document.getElementById you should use the selector you'd used above, document.querySelector.
On a side-note, read up on css selectors so you can be more specific when selecting elements using class names. Otherwise use an id if targeting a specific element.

Hide and Show DIV using strict javascript with no embedded JS or CSS

I have searched and searched over so many previously answered questions and to my surprise, NONE of them answer what I am trying to accomplish. with JQuery this is easy but I am struggling with strict javascript.
I cannot have any embedded JS OR CSS in the html...
This is what I have so far:
function showhide()
{
var billingaddress = document.getElementById("billingaddress");
if (billingaddress.style.display === "block")
{
billingaddress.style.display = "none";
}
else if (billingaddress.style.display === "none")
{
billingaddress.style.display = "block";
}
}
function init ()
{
var billingcheckbox = document.getElementById("billing");
if (billingcheckbox.checked)
{
showhide();
}
else
{
showhide();
}
It is hidden by default using CSS.
Cheers,
With he code you've provided, it can be done like this.
billingaddress.style.display is empty by default, you can easily check it in the if without a comparison.
function showhide() {
if (billingaddress.style.display) billingaddress.style.display = ""
else billingaddress.style.display = 'none';
}
var billingaddress = document.getElementById("billingaddress")
var billingcheckbox = document.getElementById("billing")
billingcheckbox.addEventListener('change', showhide)
billingcheckbox.checked = true
showhide()
<input type="checkbox" id="billing"/> Hide
<div id="billingaddress">Lorem Ipsum</div>
It's as easy as this:
this keyword inside event handler references checkbox element so you can get checkbox state with this.checked property.
<input type="checkbox" id="billing">
<input type="text" id="billingaddress" placeholder="Address" style="display:none">
<script>
var billingAddress = document.getElementById("billingaddress");
var billingCheckbox = document.getElementById("billing");
billingCheckbox.addEventListener('click', function(event) {
billingAddress.style.display = this.checked ? "block" : "none";
})
</script>
The code below should do it -- but to be sure make sure all your IDs are matching up with what is in the HTML markup:
function showhide(show) {
var billingaddress = document.getElementById("billingaddress");
if (show) {
billingaddress.style.display = "block";
} else {
billingaddress.style.display = "none";
}
}
function init () {
var billingcheckbox = document.getElementById("billing");
if (billingcheckbox.checked) {
showhide(true);
} else {
showhide(false);
}
}

Dynamically detect textarea empty or not

I'm trying to dynamically detect if a textarea is empty or not. I'm doing this so I can show a send button only when there's text entered in the textarea.
I tried this code below, but it's not working.
var text = document.getElementById("text").value;
if (text !== ''){
alert("works");
document.getElementById("sendicon1").style.display = "none";
document.getElementById("sendicon2").style.display = "inline";
}
else{
alert("not working");
document.getElementById("sendicon2").style.display = "none";
document.getElementById("sendicon1").style.display = "inline";
}
Are you putting that code inside an onkeyup or onchange function? You could do something like:
window.onload = function() {
var text = document.getElementById("text");
var func = function() {
if (text.value !== '') {
alert("works");
document.getElementById("sendicon1").style.display = "none";
document.getElementById("sendicon2").style.display = "inline";
} else {
alert("not working");
document.getElementById("sendicon2").style.display = "none";
document.getElementById("sendicon1").style.display = "inline";
}
}
text.onkeyup = func;
text.onchange = func;
}
You don't need both the onkeyup and onchange, it depends on when you are looking for it to fire. onchange will be after you have taken focus away (blur) and onkeyup will be after each key is pressed inside the textarea.
It's very easy with input event.
var textarea = document.getElementById("text");
textarea.addEventListener('input', hideOnEmpty);
function hideOnEmpty() {
var text = this.value;
if (text !== ''){
alert("works");
document.getElementById("sendicon1").style.display = "none";
document.getElementById("sendicon2").style.display = "inline";
}
else{
alert("not working");
document.getElementById("sendicon2").style.display = "none";
document.getElementById("sendicon1").style.display = "inline";
}
}
See input event documentation for further details (MDN, W3schools). This code will fire hideOnEmpty function every time that content of textarea is changed.
Beware - this code will not work in IE8 or lower, and can fail to detect deletions in IE9 (but there is no reliable way to check if input has changed without polling in IE9).
You haven't listed jQuery as a dependency, but this is definitely an area where it would come it handy.
$('#text').on('input propertychange', function () {
if ($(this).val() !== "") {
$("#sendicon1").hide();
$("#sendicon2").show();
}
else {
$("#sendicon2").hide();
$("#sendicon1").show();
}
});
The input event will detect all changes to the textarea- key presses, copying and pasting, and more.

Categories