I'm trying to execute a function but only if a pop up is displayed or not. I've used Chrome Dev Tools to find the pop up element:
<div class="modal large popup is-visible" id="verifyIdentity" data-overlay-name="verify-identity">
When I close the pop-up, this changes to the below, with the words is-visible disappearing.
<div class="modal large popup" id="verifyIdentity" data-overlay-name="verify-identity">
I have tried the following:
if ($("#modal large popup").is(':visible')) { // do something }
if ($("verifyIdentity").hasClass('.modal large popup is-visible')) { // do something }
if ($(".parentClass").hasClass('.modal large popup is-visible')) { // do something }
None of these work and I am struggling to work out how to get my code to recognise that the pop-up is visible/not visible.
I'm new to JQuery and Javascript - can anyone help please?
Thanks
You are missing the # inside your selector.
This one should work properly
<button id="verifyBtn" onclick="verify()"> Verify </button>
function verify(){
if ($("#verifyIdentity").hasClass('is-visible')) { }
console.log("works");
}
Check with console.log("works"); if the function is executed properly.
Your has class approach is probably best here, however in the 'selector' for that example you're missing the actual 'ID' selector. Try:
if ($("#verifyIdentity").hasClass('is-visible')) { // do something }
You can also just target the is-visible, the rest we don't care about.
hasClassDetermine whether any of the matched elements are assigned the given
class.
I don't know much about jQuery so can offer no real help there but you ought to be able to do this using the IntersectionObserver API. If you click the button it will assign a class to the modal which I hope will emulate the modal becoming visible. The output element will be updated as a result because the IntersectionObserver callback has determined that it is visible.
const out=document.querySelector('output');
const iocallback=function( entries, observer ){
entries.forEach( e=>{
if( e.isIntersecting && e.intersectionRatio > 0 ) {
out.textContent='isVisible='+e.isVisible;
} else {
out.textContent='isVisible='+e.isVisible;
}
});
}
let modal=document.getElementById( 'verifyIdentity' );
let options={
root:null,
rootMargin:'0px',
threshold:1,
delay:100,
trackVisibility:true
};
let io=new IntersectionObserver( iocallback, options );
io.observe( modal );
document.querySelector('[type="button"]').onclick=(e)=>{
modal.classList.toggle('visible');
};
body,body *{box-sizing:border-box;margin:1rem;padding:1rem}
#verifyIdentity{ display:none; border:1px solid red; }
.visible{display:block!important;}
output{border:1px solid black;}
<div id='verifyIdentity'> #modal# </div>
<output></output>
<input type='button' value='Toggle visibility' />
Related
please I am trying to create a FAQ like functionality, I have some elements hidden so when I click on a button it opens and hides it. I have been able to do this but I am not getting what I actually want. I might have done something wrong I suppose. So, there are 5 elements with the same className, this will help me target them all and run a for loop to kind of break them apart. However if I click on this button to open one of the element the other ones open.
const openBtn = document.querySelectorAll(".openBtn")
const openContent = document.querySelectorAll(".openContent")
for(btn of openBtn) {
btn.addEventListener('click', () => {
for(content of openContent) {
if (content.classList.contains('hidden')) {
content.classList.remove('hidden');
content.classList.add('flex')
} else {
content.classList.remove('flex');
content.classList.add('hidden')
}
}
})
}
So as you can see, If I click on the chevron icon for just one of the wither About Us, Careers or just any of the 5 every other one opens. How do I fix this ?
Since you aren't going to post even the most general version of your HTML, here is a general outline.
First, each button gets a data attribute for target,then each FAQ div gets an ID attribute that matches the data target attribute.
I attach the click handler to the document and look for openBTN on the clicked element. Then I loop through every OPENED div to close it. Then I get the target data attribute and add the appropriate classes.
document.addEventListener("click", function(e) {
if (e.target.classList.toString().includes("openBtn")) {
let opened = document.querySelectorAll(".openContent.flex");
opened.forEach(function(el) {
el.classList.add("hidden");
el.classList.remove("flex");
});
let target = document.querySelector(e.target.dataset.target)
target.classList.remove("hidden");
target.classList.add("flex");
}
});
.hidden {
display: none
}
<button data-target="#faq1" class="openBtn">OPEN</button>
<div id="faq1" class="openContent hidden">1</div>
<button data-target="#faq2" class="openBtn">OPEN</button>
<div id="faq2" class="openContent hidden">2</div>
<button data-target="#faq3" class="openBtn">OPEN</button>
<div id="faq3" class="openContent hidden">3</div>
<button data-target="#faq4" class="openBtn">OPEN</button>
<div id="faq4" class="openContent hidden">4</div>
I am trying to click on the div class (_2wP_Y) below programatically in order to open a part of the screen which display certain content using javascript internally.
<div class="_2wP_Y" style="z-index: 3; height: 72px; transform: translateY(72px);">
<div tabindex="-1">
<div class="_2EXPL CxUIE _1f1zm">
....
....
</div>
</div>
</div>
I tried various ways to click on HTMLDivElement object. Console log printing on website as clicked but on screen it doesn't get clicked automatically.
Codes I tried
var HTMLDivElement = document.getElementsByClassName('_2wP_Y')
HTMLDivElement.onclick = function() {
console.log("Clicked " );
}
var clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
HTMLDivElement.dispatchEvent(clickEvent);
It prints Clicked on console.
I also tried HTMLDivElement.click();
It also print Clicked on console, but click doesn't happen on browser.
There is multiple div having same class name(_2wP_Y) and I am using Chrome for testing in Ubuntu.
Basically I am trying to click on div on left side part of the image below to open the groups messages content in the middle of the section.
i hope this will work, happy coding :)
var HTMLDivElement = document.getElementsByClassName('_2wP_Y')
HTMLDivElement[0].addEventListener("onclick", function(){
console.log("clicked")
HTMLDivElement[0].style.backgroundColor = "red";
})
HTMLDivElement[0].dispatchEvent(new Event("onclick"));
<div class="_2wP_Y" style="z-index: 3; height: 72px; transform: translateY(72px);">
<div tabindex="-1">
<div class="_2EXPL CxUIE _1f1zm">
....
....
</div>
</div>
The problem could be that the dom is not yet loaded, resulting in the onclick event not really being attached to the DOM element. Another issue could be that getElementsByClassName returns an array and not a single element (like getElementById would). So if you only have one object with that particular class, you can just use HTMLDivElement[0]
Try to wrap everything within window.onload = function() {};:
window.onload = function() {
var HTMLDivElement = document.getElementsByClassName('_2wP_Y');
HTMLDivElement[0].onclick = function() {
console.log("Clicked");
}
}
Use jQuery.
//handling click event
$("._2wP_Y").click(function() {
alert("I was clicked");
})
//click itself
$("._2wP_Y").click();
<div class="_2wP_Y">i was clicked</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm appending some HTML to my button on a click, like this:
jQuery(document).ready(function($) {
$('#sprout-view-grant-access-button').on('click', function(e) {
$(this).toggleClass('request-help-cta-transition', 1000, 'easeOutSine');
var callback = $(e.currentTarget).attr('data-grant-access-callback');
var wrapper = $('.dynamic-container');
console.log(wrapper);
if( typeof window[callback] !== 'function') {
console.log('Callback not exist: %s', callback);
}
var already_exists = wrapper.find('.main-grant-access');
console.log(already_exists);
if( already_exists.length ) {
already_exists.remove();
}
var markup = $(window[callback](e.currentTarget));
wrapper.append(markup);
});
});
function generate_grant_access_container_markup() {
var contact_data_array = contact_data;
var template = jQuery('#template-sprout-grant-access-container')
return mustache(template.html(), {
test: 's'
});
}
As per the code, whatever comes from generate_grant_access_container_markup will be put inside dynamic-container and shown.
My problem is that, the newly added code just doesn't wanna dissapear upon clicking (toggle) of the button once again.
Here's my syntax / mustache template:
<script type="template/mustache" id="template-sprout-grant-access-container">
<p class="main-grant-access">{{{test}}}</p>
</script>
And here's the container:
<div class="button-nice request-help-cta" id="sprout-view-grant-access-button" data-grant-access-callback="generate_grant_access_container_markup">
Grant Devs Access
<div class="dynamic-container"></div>
</div>
I understand that the click event only knows about items that are in the DOM at the moment of the click, but how can I make it aware of everything that gets added after?
I would recommend visibility: hidden. Both display none and removing elements from the dom mess with the flow of the website. You can be sure you would not affect the design with visibility: hidden.
I don't deal with Jquery at all but it seems like this Stack overflow covers the method to set it up well.
Equivalent of jQuery .hide() to set visibility: hidden
Sorry if this is a really noobish question but I have just made a form with sections that are toggle-able. Each section has a '.header' which on click will perform a slideToggle on the section div.
I would like to add a triangle either pointing down or sideways to let people know it is toggle-able. (i.e ▶ or ▼).
I have the triangle in a span with the class '.arrowTog'
I was able to get partial success with
$('.header').on('click', function() {
if ($('.arrowTog').text().contains('▼')){
$('.arrowTog').text('▶');
}else{
$('.arrowTog').text('▼');
}
});
When I clicked on one all of the triangles swapped so I tried this (which causes none of them to rotate at all):
$('.header').on('click', function() {
if ($(this).prev('.arrowTog').text().contains('▼')){
$(this).prev('.arrowTog').text('▶');
}else{
$(this).prev('.arrowTog').text('▼');
}
});
This is a sample of the HTML
<div class="header" style="cursor: pointer;">
<span class="arrowTog">▶ </span>
<b>Merchant</b>
</div>
<div class="searchContent" style="display:none;">
Any ideas what I am doing wrong?
Thanks!
In your first version, the problem is you're finding every .arrowTog in the page. You can use the fact that within the click handler, this is bound to the element that was clicked, and then just search within that using find:
$('.header').on('click', function() {
var arrow = $(this).find('.arrowTog');
if (arrow.text().contains('▼')){
arrow.text('▶');
} else {
arrow.text('▼');
}
});
You're using a class. You probably have a number of elements with the same class in it, so jQuery is matching all of them and doing this transformation to all of them.
Use a context (All .arrowTog RIGHT INSIDE THIS NODE):
$('.header').on('click', function(evt) {
if ($('.arrowTog', evt.target).text().contains('▼')){
$('.arrowTog', evt.target).text('▶');
}else{
$('.arrowTog', evt.target).text('▼');
}
});
Why not use CSS?
.arrowTog:before {
content: '▶';
}
.arrowTog.open:before {
content: '▼';
}
And then
$('.header').on('click', function() {
$(this).toggleClass('open');
});
I'm making a website where I want a window that pops up and when I click on the X it closes by making its css a display:none;
This is my HTML:
<div id="PortOverlay"></div>
<div id="PortContainer">
<div id="poCross">X</div>
</div>
This is my CSS:
#PortOverlay {width:100%;height:100%;top:0px;left:0px;position:fixed;z-index:10;background-color:#222;opacity:0.4;display:block;}
#PortContainer {width:800px;height:auto;min-height:800px;position:fixed;margin:18px auto;background:#FFF;border-radius:10px;box-shadow:0px 0px 1px 1px #888;}
#PortContainer > div#poCross {width:auto;height:auto;font-family:arial;font-weight:bolder;font-family:16px;margin:15px;}
#PortContainer > div#poContent {}
This is my JS:
var poCross, PortContainer, PortOverlay;
function poClose(){
poCross = document.getElementById('poCross');
PortContainer = document.getElementById('PortContainer');
PortOverlay = document.getElementById('PortOverlay');
if (poCross.click()) {
PortContainer.style.display = "none";
PortOverlay.style.display = "none";
alert('test'); // Alert included for testing //
}
}
I've even included an alert to test if it was just a CSS problem but this doesn't react also.
Thanks for the help.
(I'm Dutch and 15 so sorry for wrong grammar orso )
The code you have only runs when the page is loaded. At that time, your DOM element exists, but click() will always return false, and the code will never be evaluated again.
What you want is an onClick event handler. Event handlers run when the event occurs, not when the code is loaded for the first time.