This may seem like a really simple question, but I'm having a lot of trouble trying to get it to work.
I have a series of elements spread across different parts of a page.
<span class="click-element"><span>
---
<span class="click-element"><span>
--
<span class="click-element"><span>
I want to toggle a class ("active") on/off on each of them when they are clicked individually, this should also remove the class from all the others.
To do this, my function looks like this:
var targets = document.querySelectorAll('.click-element');
for (i = 0; i < targets.length; i++) {
targets[i].addEventListener('click', function () {
var clicked = this;
if (this.classList.contains("active")) {
[].forEach.call(targets, function (a) {a.classList['remove']('active');});
}
else {
[].forEach.call(targets, function (a) {a.classList[a == clicked ? 'add' : 'remove']('active');});
}
});
}
But what I'm trying to do, is then remove the class when anything else is clicked in the document:
document.addEventListener('click', function () {
document.querySelector('.click-element.active').classList.remove("active");
});
However, the problem I'm having is the second event seems to just override the first. How can I fix this? Or is there a cleaner approach to do what I want?
No jQuery thanks
try to cancle the event bubbling like this:
for (i = 0; i < targets.length; i++) {
targets[i].addEventListener('click', function(e) {
var clicked = this;
if (this.classList.contains("active")) {
[].forEach.call(targets, function(a) {
a.classList['remove']('active');
});
}
else {
[].forEach.call(targets, function(a) {
a.classList[a == clicked ? 'add' : 'remove']('active');
});
}
e.stopPropagation();
});
}
Keys:
targets[i].addEventListener('click', function(e) {...
e.stopPropagation();...
Try this :
var targets = document.querySelectorAll('.click-element');
var activeElement; // this should be some global variable
for (i = 0; i < targets.length; i++) {
targets[i].addEventListener('click', function () {
if(activeElement){
activeElement.classList['remove']('active');
}
var clicked = this;
activeElement = this;
if (this.classList.contains("active")) {
[].forEach.call(targets, function (a) {a.classList['remove']('active');});
}
else {
[].forEach.call(targets, function (a) {a.classList[a == clicked ? 'add' : 'remove']('active');});
}
});
}
I think better solution will be to use event bubbling.
If you have a common container:
document.getElementById('#containerId').addEventListener('click', function(evt){
var element = evt.target;
if(element.classList.contains('click-element'){
//toggle active
element.classList[element.classList.contains('active') ? 'add' : 'remove']('active');
} else{
//remove the active from all elements
document.querySelectorAll('.click-element.active').forEach(
function (clickElement, index) {clickElement.classList[remove]('active')}
);
}
});
In your case you don't have child elements in the spans, but if you had you need to check if the clicked element is a descendant of the span.
try jQuery libraries it will make it easy
$( "span" ).removeClass( "yourClass" );
http://api.jquery.com/removeclass/
Related
How can I disable a anchor link if one(1) of my six(6) checkbox is not check?
var first_option = $('#pid-1590083, #pid-1590090, #pid-1590091, #pid-1590092, #pid-1590093, #pid-1590094');
$("a").click(function(e) {
if($("first_option").prop("checked") === false) {
e.preventDefault(); return false;
} else {return true;};
});
Your current logic doesn't work as you're only looking at the checked property of the first element you select, not all of them.
To achieve what you require, you can use the :checked selector to get all the checked elements within the selectors you provide, then check the length property of the result to see if there aren't any. Try this:
var $first_option = $('#pid-1590083, #pid-1590090, #pid-1590091, #pid-1590092, #pid-1590093, #pid-1590094');
$("#tmp_button-99035").click(function(e) {
if ($first_option.filter(':checked').length === 0) {
e.preventDefault();
alert('Please Choose Collar Colour To Continue');
};
});
first_option.prop("checked") will always check for first element. What you have to do is loop over all elements to check
Like this
$("#tmp_button-99035").click(function(e) {
var isChecked = false;
for (var i = 0; i < first_option.length; i++) {
if (first_option.eq(i).prop("checked")) {
isChecked = true;
break;
}
}
if (!isChecked) {
alert('Please Choose Collar Colour To Continue');
e.preventDefault();
}
return isChecked;
});
Well, the js snippet of yours is only checking the first element. So, you have to track other checkboxes as well for correct result.
var first_option = $('#pid-1590083, #pid-1590090, #pid-1590091, #pid-1590092, #pid-1590093, #pid-1590094')
$(document).on('click', '#tmp_button-99035', function (e) {
if ($(first_option).filter(":checked").length == 0) {
e.preventDefault();
}
});
I have several of these lines in my HTML:
<img src="Iconos/heart.png" alt="Fave" class="fave_icon">
I want to change the 'src' when one of them is clicked (but ONLY on that one)
I tried this but it does not work:
$(document).on('click', '.fave_icon', function (event) {
if ($(this).getAttribute('src') == "Iconos/heart.png")
{
$(this).src = "Iconos/heart_coloured.png";
}
else
{
$(this).src = "Iconos/heart.png";
}
});
this is the function you're in.
The clicked element is event.target. Replace $(this) with $(event.target) and it will work.
For the general case, where the targeted element has children, it's possible that the target of your click is a child (of .fave_icon). Use closest() to target the closest .fave-icon:
$(document).on('click', '.fave_icon', function(event) {
let elem = $(event.target).closest('.fave_icon');
if (elem.getAttribute('src') == "Iconos/heart.png") {
elem.src = "Iconos/heart_coloured.png";
} else {
elem.src = "Iconos/heart.png";
}
});
I ended up solving it like this:
<img src="Iconos/heart.png" onclick="fav(this);" alt="Fave" class="fave_icon">
And then
function fav(heart){
if (heart.getAttribute('src') == "Iconos/heart.png")
{
heart.src = "Iconos/heart_coloured.png";
}
else
{
heart.src = "Iconos/heart.png";
}
I want to have a sequential list display, where initially all the lis except the first one are hidden, and when the user clicks a button, the lis appear by groups of 3. Eventually I would like to hide the button when the list gets to the end.
The code is something like this, but it shows only one per click, every third - but I want to show also the in-between elements until the third
jQuery(".event-holder:gt(0)").hide();
var i = 0;
var numbofelem = jQuery(".event-holder").length;
jQuery("#allevents").on('click', function(e){
e.preventDefault();
i+=3;
jQuery(".event-holder").eq(i).fadeIn();
if ( i == numbofelem ) { jQuery(this).hide(); }
});
Probably the .eq(i) is not the function I need, but couldn't find the correct one...
You can use :hidden with use of .each() loop:
jQuery("#allevents").on('click', function(e){
e.preventDefault();
jQuery(".event-holder:hidden").each(function(i){
if(i <= 2){
jQuery(this).fadeIn();
}
});
});
Working fiddle
If you have just three you could use :
jQuery(".event-holder:gt(0)").hide();
var i = 0;
var numbofelem = jQuery(".event-holder").length;
var li = jQuery(".event-holder");
jQuery("#allevents").on('click', function(e){
e.preventDefault();
li.eq(i+1).fadeIn();
li.eq(i+2).fadeIn();
li.eq(i+3).fadeIn();
i+=3;
if ( i == numbofelem ) { jQuery(this).hide(); }
});
If you have several lis to show you could use a loop, e.g :
var step = 10; //Define it outside of the event
for(var j=0;j<step;j++){
li.eq(i+j).fadeIn();
}
i+=step;
Hope this helps.
You eq(i) needs to be looped.
jQuery(".event-holder:gt(0)").hide();
var i = 0;
var numbofelem = jQuery(".event-holder").length;
jQuery("#allevents").on('click', function(e){
e.preventDefault();
//i+=3;
//jQuery(".event-holder").eq(i).fadeIn();//You are showing only the third element. Loop this
//Something like this
for(var j=i;j<i+3;j++){
jQuery(".event-holder").eq(i).fadeIn();
if ( i == numbofelem ) { jQuery(this).hide(); }
}
i = j;
});
An alternative approach would be to buffer all the items, and keep adding them until empty:
var holders = $('.event-holder').hide();
$("#allevents").click( function(e){
e.preventDefault();
holders = holders.not(holders.slice(0, 3).fadeIn());
if(holders.length === 0) $(this).hide();
});
Fiddle
I have two different example one have mouseover functionality and other have click event functionality but now i want both together below are the description:
Mouseover Example Link: http://wheaton.advisorproducts.com/investment-advisory
Mouse click Example : http://ivyfa.advisorproducts.com/financial-planning-process
Requirement are like this
In this example ( http://ivyfa.advisorproducts.com/financial-planning-process ) right now mouseover functionality is working but now i want below functionality:
When user move mouse over the images then in center thier related text will be visible both for funnel and below circle example.
If user click on any of the image section then their related text will be visible everytime untill user click on another image or portion.
Along with this click event when user mousehover on diif-2 images section then also thier related text will be visible , when user move mouse out of the circle then the selcted text will be shown.
In the end i want to merge both the examples
Its very complicated to explain this example sorry for that :(
Below is the js code used for mouseover functionality:
/*-----Only for hove over image -show hide text------*/
var IdAry=['slide1','slide2','slide3','slide4'];
window.onload=function() {
for (var zxc0=0;zxc0<IdAry.length;zxc0++){
var el=document.getElementById(IdAry[zxc0]);
if (el){
el.onmouseover=function() {
changeText(this,'hide','show')
}
el.onmouseout=function() {
changeText(this,'show','hide');
}
}
}
}
function changeText(obj,cl1,cl2) {
obj.getElementsByTagName('SPAN')[0].className=cl1;
obj.getElementsByTagName('SPAN')[1].className=cl2;
}
Below is the js code used for click event functionality:
/*----------Text change on click - Our Process page---------------*/
var prev;
var IdAry = ['slide1', 'slide2', 'slide3', 'slide4'];
window.onload = function () {
for (var zxc0 = 0; zxc0 < IdAry.length; zxc0++) {
var el = document.getElementById(IdAry[zxc0]);
if (el) {
setUpHandler(el);
el.onmouseover = function () {
changeText(this,'hide','show')
}
el.onmouseout = function () {
changeText(this,'show','hide');
}
}
}
}
/*---------This is used to add selected class on clicked id only and remove class selected from rest---------*/
function setUpHandler(el) {
$("#" + IdAry.join(",#")).click(function () {
$(this).addClass("selected");
$("#graphics .selected").not(this).removeClass("selected");
})
/*---------This will add show hide class to thier spans and vise versa-------*/
$("#" + IdAry.join(",#")).click(
function () {
changeText(this, "hide", "show");
clearSelection();
},
function () {
changeText(this, "show", "hide");
clearSelection();
})
}
function changeText(obj, cl1, cl2) {
obj.getElementsByTagName('SPAN')[0].className = "hide";
obj.getElementsByTagName('SPAN')[1].className = "show";
if (prev && obj !== prev) {
prev.getElementsByTagName('SPAN')[0].className = "show";
prev.getElementsByTagName('SPAN')[1].className = "hide";
}
prev = obj
}
function clearSelection() {
if (window.getSelection) window.getSelection().removeAllRanges();
else if (document.selection) document.selection.empty();
}
Thanks
Sushil
You can add multiple event names to the same assignment:
$(document).on('mouseover click', '.yourObject', function (event) {
if (event.type === "mouseover") {
// Mouse-Over code here
} else if (event.type === "click") {
// Click code here
}
});
Also, try to use addEventListener instead of hardcoding events like el.onmouseout=function(){...}
use:
el.addEventListener("mouseout", function () {...});
That'll make it easier to manage the events (Remove them, for example), should that be needed.
You can add multiple events to a DOM by using
$(document).on('mouseover','.yourObject', function(){ //over code })
.on('click', '.yourObject', function() { //click code});
The problem with your code is that you are setting window.onload twice.
Since your are using jQuery you can make it work by binding on document.ready event.
//first sample
(function($){
/*-----Only for hove over image -show hide text------*/
var IdAry=['slide1','slide2','slide3','slide4'];
$(function() {
for (var zxc0=0;zxc0<IdAry.length;zxc0++){
var el=document.getElementById(IdAry[zxc0]);
if (el){
el.onmouseover=function() {
changeText(this,'hide','show')
}
el.onmouseout=function() {
changeText(this,'show','hide');
}
}
}
});
function changeText(obj,cl1,cl2) {
obj.getElementsByTagName('SPAN')[0].className=cl1;
obj.getElementsByTagName('SPAN')[1].className=cl2;
}
}(jQuery));
//second sample
(function($){
/*----------Text change on click - Our Process page---------------*/
var prev;
var IdAry = ['slide1', 'slide2', 'slide3', 'slide4'];
$(function () {
for (var zxc0 = 0; zxc0 < IdAry.length; zxc0++) {
var el = document.getElementById(IdAry[zxc0]);
if (el) {
setUpHandler(el);
el.onmouseover = function () {
changeText(this,'hide','show')
}
el.onmouseout = function () {
changeText(this,'show','hide');
}
}
}
});
/*---------This is used to add selected class on clicked id only and remove class selected from rest---------*/
function setUpHandler(el) {
$("#" + IdAry.join(",#")).click(function () {
$(this).addClass("selected");
$("#graphics .selected").not(this).removeClass("selected");
})
/*---------This will add show hide class to thier spans and vise versa-------*/
$("#" + IdAry.join(",#")).click(
function () {
changeText(this, "hide", "show");
clearSelection();
},
function () {
changeText(this, "show", "hide");
clearSelection();
})
}
function changeText(obj, cl1, cl2) {
obj.getElementsByTagName('SPAN')[0].className = "hide";
obj.getElementsByTagName('SPAN')[1].className = "show";
if (prev && obj !== prev) {
prev.getElementsByTagName('SPAN')[0].className = "show";
prev.getElementsByTagName('SPAN')[1].className = "hide";
}
prev = obj
}
function clearSelection() {
if (window.getSelection) window.getSelection().removeAllRanges();
else if (document.selection) document.selection.empty();
}
}(jQuery));
$(document).click(function(evt) {
var target = evt.currentTarget;
var inside = $(".menuWraper");
if (target != inside) {
alert("bleep");
}
});
I am trying to figure out how to make it so that if a user clicks outside of a certain div (menuWraper), it triggers an event.. I realized I can just make every click fire an event, then check if the clicked currentTarget is same as the object selected from $(".menuWraper"). However, this doesn't work, currentTarget is HTML object(?) and $(".menuWraper") is Object object? I am very confused.
Just have your menuWraper element call event.stopPropagation() so that its click event doesn't bubble up to the document.
Try it out: http://jsfiddle.net/Py7Mu/
$(document).click(function() {
alert('clicked outside');
});
$(".menuWraper").click(function(event) {
alert('clicked inside');
event.stopPropagation();
});
http://api.jquery.com/event.stopPropagation/
Alternatively, you could return false; instead of using event.stopPropagation();
if you have child elements like dropdown menus
$('html').click(function(e) {
//if clicked element is not your element and parents aren't your div
if (e.target.id != 'your-div-id' && $(e.target).parents('#your-div-id').length == 0) {
//do stuff
}
});
The most common application here is closing on clicking the document but not when it came from within that element, for this you want to stop the bubbling, like this:
$(".menuWrapper").click(function(e) {
e.stopPropagation(); //stops click event from reaching document
});
$(document).click(function() {
$(".menuWrapper").hide(); //click came from somewhere else
});
All were doing here is preventing the click from bubbling up (via event.stopPrpagation()) when it came from within a .menuWrapper element. If this didn't happen, the click came from somewhere else, and will by default make it's way up to document, if it gets there, we hide those .menuWrapper elements.
try these..
$(document).click(function(evt) {
var target = evt.target.className;
var inside = $(".menuWraper");
//alert($(target).html());
if ($.trim(target) != '') {
if ($("." + target) != inside) {
alert("bleep");
}
}
});
$(document).click((e) => {
if ($.contains($(".the-one-you-can-click-and-should-still-open").get(0), e.target)) {
} else {
this.onClose();
}
});
I know that the question has been answered, but I hope my solution helps other people.
stopPropagation caused problems in my case, because I needed the click event for something else. Moreover, not every element should cause the div to be closed when clicked.
My solution:
$(document).click(function(e) {
if (($(e.target).closest("#mydiv").attr("id") != "mydiv") &&
$(e.target).closest("#div-exception").attr("id") != "div-exception") {
alert("Clicked outside!");
}
});
http://jsfiddle.net/NLDu3/
I do not think document fires the click event. Try using the body element to capture the click event. Might need to check on that...
This code will open the menu in question, and will setup a click listener event. When triggered it will loop through the target id's parents until it finds the menu id. If it doesn't, it will hide the menu because the user has clicked outside the menu. I've tested it and it works.
function tog_alerts(){
if($('#Element').css('display') == 'none'){
$('#Element').show();
setTimeout(function () {
document.body.addEventListener('click', Close_Alerts, false);
}, 500);
}
}
function Close_Alerts(e){
var current = e.target;
var check = 0;
while (current.parentNode){
current = current.parentNode
if(current.id == 'Element'){
check = 1;
}
}
if(check == 0){
document.body.removeEventListener('click', Close_Alerts, false);
$('#Element').hide();
}
}
function handler(event) {
var target = $(event.target);
if (!target.is("div.menuWraper")) {
alert("outside");
}
}
$("#myPage").click(handler);
try this one
$(document).click(function(event) {
if(event.target.id === 'xxx' )
return false;
else {
// do some this here
}
});
var visibleNotification = false;
function open_notification() {
if (visibleNotification == false) {
$('.notification-panel').css('visibility', 'visible');
visibleNotification = true;
} else {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
$(document).click(function (evt) {
var target = evt.target.className;
if(target!="fa fa-bell-o bell-notification")
{
var inside = $(".fa fa-bell-o bell-notification");
if ($.trim(target) != '') {
if ($("." + target) != inside) {
if (visibleNotification == true) {
$('.notification-panel').css('visibility', 'hidden');
visibleNotification = false;
}
}
}
}
});