Remove Click Event only in a specific browser view - javascript

I have a Toggle displaying content. I am trying to remove its click event in larger than 600px of browser view. That means the Toggle click functionality should not work in larger view of 600px. Following is the code i used.
HTML:
<div class="trigger">Trigger</div>
<div class="content">This is the Toggle Displaying content</div>
let trigger = document.querySelector(".trigger");
let content = document.querySelector(".content");
mobilefunction=(el)=>{
let cs = window.getComputedStyle(el).display;
if(cs==="none") {el.style.display="block"}
else {el.style.display="none";}
}
responsivemenu=()=> {
let windowwidth = window.innerWidth;
if(windowwidth < 500) {
trigger.addEventListener("click", ()=>{mobilefunction(content)});
}
else {
trigger.removeEventListener("click", ()=>{mobilefunction(content)});
}
}
window.addEventListener("resize", responsivemenu );
responsivemenu();
I am trying to make Click event enable only in mobile and remove it for desktop. Seeking for experts help on this. Thanks in Advance!

I'd recommend to not add/remove the eventlistener but just check inside the listener callback.
By doing this you can drop all the resize handler stuff as the width is validated the second you click.
let trigger = document.querySelector(".trigger");
let content = document.querySelector(".content");
mobilefunction = () => {
if (window.innerWidth >= 500) {
return;
}
let cs = window.getComputedStyle(content).display;
if (cs === "none") {
content.style.display = "block"
} else {
content.style.display = "none";
}
}
trigger.addEventListener("click", mobilefunction);
<div class="trigger">Trigger</div>
<div class="content">This is the Toggle Displaying content</div>

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";
}
});

Close menu on click outside - Vanilla JS

I created a side menu, which displays and hides when clicking the menu button. Now, I would like that the menu closes when I click outside the menu, but I cannot figure out how to do it.
I have tried adding a clicklistener to the body, but this disables the menu completely. I also thougt about getting the ID of the clicked element anywhere in the body and close the menu if clickedElement != sideBar && sideBar.style = "200px", but I cannot get it to work. Can someone help me out here? I would like to find a solution without JQuery.
menuBtn.addEventListener("click", function () {
if (sideBar.style.width == "200px") {
sideBar.style.width = "0px";
setTimeout(function () {
menuItems.style.display = "none";
}, 1000);
} else {
sideBar.style.width = "200px";
menuItems.style.display = "block";
}
});
You can add an event listener to the parent container and check if the click's target is inside the element or not, something like:
document.addEventListener("click", (e) => {
if (box.contains(e.target)) {
result.innerHTML = "inside";
} else {
result.innerHTML = "outside";
}
});
#box {
width: 100px;
height: 100px;
background-color: dodgerblue;
}
<div id="box"></div>
<div id="result"></div>

JS distinguish click and scroll on iPhone

I'm trying to close a Sidemenu onclick. however, touchstart also detects scrolling as a click, so is touchend.
how to just detect a click (not a scroll) on iPhone?
$('#html').on("click touchstart",function(e) {
var optionsmenue = $(".adminmenu_label");
if(!optionsmenue.is(e.target) && optionsmenue.has(e.target).length === 0) {
document.getElementById("Optionsmenu").style.width = "0%";
document.getElementById("Optionsmenu").style.transition = "0.2s ease-out";
document.getElementById("adblue").style.display = "block";
document.getElementById("whatever").style.display = "block";
document.getElementById("not_related").style.display = "block";
document.getElementById("still_not_related").style.display = "block";
document.getElementById("still_still_not_related").style.width = "100%";
}
});
Detecting for iOS and adding cursor:pointer works for me , IOS seems to have a problem with event delegation.
var iOS = ["iPad","iPhone","iPod"].indexOf(navigator.userAgent) > -1;
if(iOS) {
$('body').css({ cursor : 'pointer' });
}
$('#html').on("click",function(e) {
// No need for touch start click will do the trick;
});
should remove "touchstart" in
$('#html').on("click touchstart",function(e) {

Onclick javascript function working only on second click

function toggleDivFunction() {
var arrowElement = document.getElementById("arrowRight");
var showElement = document.getElementById("dropdownText");
arrowElement.onclick = function() {
if (showElement.style.display == 'none') {
showElement.style.display = 'block';
document.getElementById("arrowRight").style = "transform: rotate(+90deg)";
} else {
showElement.style.display = 'none';
document.getElementById("arrowRight").style = "transform: rotate(0deg)";
}
}
}
<p class="dropdownHeader">TOP <span id="arrowRight" class="arrowRight" onclick="toggleDivFunction();"> > </span></p>
<div class="dropdownText" id="dropdownText"><p>TEXT TO BE SHOWN</p></div>
The problem is that the dropdownText div only shows up after a second click on the arrowRight span.
I have seen it as a common problem, but still failed in finding a solution. Any help would be appreciated.
You do not need to bind a click event handler inside another click event handler. You have to use a single click event handler.
The show/hide functionality belongs to second click event handler and this is binded to your span DOM element after first click.
function toggleDivFunction () {
var arrowElement = document.getElementById ("arrowRight");
var showElement = document.getElementById ("dropdownText");
if(showElement.style.display == 'none')
{
showElement.style.display = 'block';
document.getElementById("arrowRight").style = "transform: rotate(+90deg)";
}
else
{
showElement.style.display = 'none';
document.getElementById("arrowRight").style = "transform: rotate(0deg)";
}
}
<p class="dropdownHeader">TOP <span id="arrowRight" class="arrowRight" onclick="toggleDivFunction();"> > </span></p>
<div class="dropdownText" id="dropdownText">
<p>TEXT TO BE SHOWN</p></div>
Just adding to approved answer.
Check for showElement.style.display == ''.
Additionally, for switching to flex on first click itself, if you are using display = 'none' as default.
Example:
..
if (showElement.style.display == 'none' || showElement.style.display == '') {
..
if the style of text is display = 'none'.
You want to assign your event handlers earlier:
window.onload=toggleDivFunction;
and remove the onclick='toggleDivFunction()', its unneccessary then and oldfashioned.
Your code assigns a listener when an event is triggered (toggleDivFunction). To trigger the listener (arrowElement.onclick) you need to cause another event doing a second click.
remove the arrowElement.onclick = function() {}
Why?
you have already apply the function in onclick=toggleDivFunction() with arrowRight .so
first execute the toggleDivFunction() then to perform the Dom arrowElement.onclick .use any one of the onclick function ,not both
function toggleDivFunction() {
var arrowElement = document.getElementById("arrowRight");
var showElement = document.getElementById("dropdownText");
if (showElement.style.display == 'none') {
showElement.style.display = 'block';
document.getElementById("arrowRight").style = "transform: rotate(+90deg)";
} else {
showElement.style.display = 'none';
document.getElementById("arrowRight").style = "transform: rotate(0deg)";
}
}
<p class="dropdownHeader">TOP <span id="arrowRight" class="arrowRight" onclick="toggleDivFunction();"> > </span></p>
<div class="dropdownText" id="dropdownText">
<p>TEXT TO BE SHOWN</p>
</div>

Javascript click event requires double clicks

I have a simple HTML-CSS-JavaScript page with an event listener on a button to toggle a div.
However, all is working but the animation function takes two clicks first time to work, although i consoled the click event to prove that the button listens to the first click too.
i tried to wrap into window.onload but same thing.
note: i want to use pure javascript only.
thank you
this pic shows the first click (it says "clicked" in the console):
this pic shows the second click (animation took place):
Here is my code:
var showDivButton = document.getElementById('showDivButton');
var info = document.getElementById('info');
showDivButton.addEventListener('click', animation) ;
// animation func
function animation () {
console.log('Clicked!');
if (info.style.display === 'none'){
info.style.display = 'inline-block';
showDivButton.style.background = 'green';
} else {
info.style.display = 'none';
showDivButton.style.background = 'gray';
}
}
Look at My Plunker Here please. Thank you in advance.
Try to revise your function block as follow:
function animation () {
console.log('Clicked!');
if (info.style.display == '' || info.style.display == 'none'){
info.style.display = 'inline-block';
showDivButton.style.background = 'green';
} else {
info.style.display = 'none';
showDivButton.style.background = 'gray';
}
}
info.style.display is '' on initial
Because info.style.display refers to the style attribute of your div, not the computed Style, so on the first click, this is not set.
You may want to look at getComputedStyle, but i would advise switching class instead of directly modifying style.

Categories