jQuery continuously running an event - javascript

I have the following code which checks for the id of the active tab BUT only once when the page initially loads.
jQuery(document).ready(function(){
var id_of_tab = jQuery('#member-registration .tab-pane.active').attr('id');
console.log(id_of_tab);
});
I need this code to continuously check for the id of the active tab, (as there are various ways in which the user can make this tab active, and I have tried many click and hover events but ive found issues with all of them).
Rather than firing on a click/hover (such as the example below) the code needs to simple needs to keep running and to change the variable value if the active tab changes.
jQuery(document).ready(function(){
$( ".view-registration" ).hover(
function() {
var id_of_tab = jQuery('#member-registration .tab-pane.active').attr('id');
console.log(id_of_tab);
});
});
I'm struggling on this one!

You can bind multiple events on one function handler.
The 4 I suggest here are only suggestion for the code example`
It's up to you to determine the right events to bind.
See list here: http://www.quirksmode.org/dom/events/
$(document).ready(function(){
$( "#member-registration" ).bind("change mouseover click input",function(){
var id_of_tab = $(this).attr('id'); // Will alway return #member-registration
console.log(id_of_tab);
// Suggested console message ;)
console.log("An event occured on #member-registration");
// Maybe a check for the `active` class?
if( $(this).hasClass("active") ){
console.log("#member-registration is active.");
}
});
});

Related

jQuery selectors not working with added class

I'm working on a php/jQuery store and have run into the following problem:
I have a few div boxes as articles and as soon as a box is clicked, it is moved into the shopping cart and therefore has to become inactive.
That's my code so far:
$( ".artbox" ).not( ".inactive" ).on('click', function(){
$(this).addClass("inactive");
$(this).find("#artbox").addClass("inactive")
})
It adds the class .inactive to two div objects, which are positioned inside each other. The rest of this function is left out here to keep it short. The problem is that while the according styles for .inactive are applied, I can still click on the box again and again and the function will be called again and again (although I have added the .not() selector) which results in having this specific article in the shopping cart multiple times - and this is what I would like to prevent. If I reload the page manually everything is fine and this
$( ".artbox.inactive" ).on('click', function(){
$(this).effect( "shake", {distance:1});
})
works, too (it doesn't for the items added without reloading).
But I am looking for a solution that works without reloading because I am displaying a popup window with a sucess message after the item was added to the cart.
JSFiddle
I've tried this here https://stackoverflow.com/a/12202186/2842292 but unfortunatly can't get it to work in my example.
Thanks in advance!
You can do it in two ways:
You unregister the event listener upon the click.
You can do it adding this to the event listener: $(this).unbind();,
You add an additional check at the very top of the listener:
if($(this).hasClass("inactive")) return;
Then if it even runs, it will quit and will not do the job.
The eventbinding happens on page load, so you should build the logic in the function:
$( ".artbox" ).on('click', function() {
if ($(this).hasClass("inactive")) {
$(this).effect( "shake", {distance:1});
} else {
$(this).addClass("inactive");
$(this).find("#artbox").addClass("inactive");
}
});

Focus out of a div but not if a div was pressed - Jquery

I have a unique situation here that I am trying to figure out. Here is what I am doing:
$( ".add-user-group" )
.focusout(function(e) {
$(this).parent().find(".search-overhang").hide();
})
.focus(function() {
$(this).parent().find(".search-overhang").show();
});
I am listening for when this input is selected to show a results container that is populated with a server call using ajax Now within that ajax call I am populating data using:
dataSent.parent().find(".search-overhang").html('');
for(var i = 0; i < data.data_retrieved.length; i++)
{
dataSent.parent().find(".search-overhang").append("<span class='overhang-data'><span>"+data.data_retrieved[i].display_name+"</span><br/><span class='bottom-inside-overhang-data'>"+data.data_retrieved[i].user_email+"</span></span>");
}
$(".overhang-data").on('click',function(event){
event.stopPropagation();
});
Now you will notice I have a on click that should override the focusout on the add-user-group. But this is not the case. Before it has a chance to do so it stops because I stop the event action using the focusout. What I am trying to figure out is how can I override this, even with my data being dynamically populated? Note one thing: add-user-group is loaded server side before page loads.
Suggestions, thoughts?
After looking further I found a quick solution:
var clicked = '';
$(document).on('mousedown',function(event){
clicked = $(event.target).attr("class");
});
..
.focusout(function(event) {
if(clicked !== "overhang-data")
{
$(this).parent().find(".search-overhang").hide();
}
})..
I am just listening on a global scale for what is clicked and storing that into a variable so when I need to check on the focusout I can verify if it is the corresponding class.

Javascript onclick requiring two clicks

I have this box that transforms in a bigger box when clicked (getting class).
But it is taking 2 clicks, and not only one as it was suposed to take.
.clientes {width:170px;height:27px;background-image:url('../imagens/clients.gif');-webkit-transition:1s;}
.clientes-clicked {width:356px !important;height:154px !important;background-image:url('../imagens/clients-big.png') !important;-webkit-transition:1s;}
<script>
var clientesclick = function(){
$('.clientes').on('click', function(e) {
$('.clientes').toggleClass("clientes-clicked"); //you can list several class names
e.preventDefault();
});
}
</script>
You're making this more complicated than it needs to be. You could simply do:
$('.clientes').click(function(){
$(this).toggleClass('clientes-clicked');
});
A fiddle: http://jsfiddle.net/64XQ3/
And, as was pointed out above, your jQuery should be wrapped in
$(document).ready(function(){
// code here
});
Try it like this
<script>
$(document).ready(function() {
$('.clientes').on('click', function(e) {
$('.clientes').toggleClass("clientes-clicked"); //you can list several class names
e.preventDefault();
});
});
</script>
Not too sure why you are assigning it to a variable but it would not run right away, instead it will be executed when you call that method (I guess this is first click) and then afterwards your dom elements will have the event (second click).
Using $(document).ready it will run once all the dom is ready, then when you first click on your elements they should already have the event

How defined in jQuery was it a regular click on the same element or double-click?

How can I define in jQuery was it a regular click on the same element or double-click?
For example we have element like this:
<div id="here">Click me once or twice</div>
And we need to perform different actions after regular click and double-click.
I tried something like this:
$("#here").dblclick(function(){
alert('Double click');
});
$("#here").click(function(){
alert('Click');
});
But, of course, it doesn't work, everytime works only 'click'.
Then, some people showed me this:
var clickCounter = new Array();
$('#here').click(function () {
clickCounter.push('true');
setTimeout('clickCounter.pop()', 50);
if (clickCounter.length > 2) {
//double click
clickCounter = new Array(); //drop array
} else {
//click
clickCounter = new Array(); //drop array !bug ovethere
}
});
Here we tried to set the interval between clicks, and then keep track of two consecutive events, but this have one problem.. it doesn't work too.
So, someone knows how to do this? or can someone share a link to the material, where I can read about it?
From QuirksMode:
Dblclick
The dblclick event is rarely used. Even when you use it, you should be
sure never to register both an onclick and an ondblclick event handler
on the same HTML element. Finding out what the user has actually done
is nearly impossible if you register both.
After all, when the user double–clicks on an element one click event
takes place before the dblclick. Besides, in Netscape the second click
event is also separately handled before the dblclick. Finally, alerts
are dangerous here, too.
So keep your clicks and dblclicks well separated to avoid
complications.
(emphasis mine)
What you are doing in your question, is exactly how it should be done.
$(".test").click(function() {
$("body").append("you clicked me<br />");
});
$(".test").dblclick(function() {
$("body").append("you doubleclicked me<br />");
});
It works and here is an demo for that.
Since, you want to detect separate single double click. There is a git project for this.
$("button").single_double_click(function () {
alert("Try double-clicking me!")
}, function () {
alert("Double click detected, I'm hiding")
$(this).hide()
})
It adds up events to detect single double clicks.
Hope it helps you now.

jQuery: Can't cache onclick handler?

I've got a step-by-step wizard kind of flow where after each step the information that the user entered for that step collapses down into a brief summary view, and a "Go back" link appears next to it, allowing the user to jump back to that step in the flow if they decide they want to change something.
The problem is, I don't want the "Go Back" links to be clickable while the wizard is animating. To accomplish this I am using a trick that I have used many times before; caching the onclick handler to a different property when I want it to be disabled, and then restoring it when I want it to become clickable again. This is the first time I have tried doing this with jQuery, and for some reason it is not working. My disabling code is:
jQuery.each($("a.goBackLink"), function() {
this._oldOnclick = this.onclick;
this.onclick = function() {alert("disabled!!!");};
$(this).css("color", "lightGray ! important");
});
...and my enabling code is:
jQuery.each($("a.goBackLink"), function() {
this.onclick = this._oldOnclick;
$(this).css("color", "#0000CC ! important");
});
I'm not sure why it's not working (these are good, old-fashioned onclick handlers defined using the onclick attribute on the corresponding link tags). After disabling the links I always get the "disabled!!!" message when clicking them, even after I run the code that should re-enable them. Any ideas?
One other minor issue with this code is that the css() call to change the link color also doesn't appear to be working.
I wouldn't bother swapping around your click handlers. Instead, try adding a conditional check inside of the click handler to see if some target element is currently animating.
if ($('#someElement:animated').length == 0)
{
// nothing is animating, go ahead and do stuff
}
You could probably make this a bit more concise but it should give you an idea... Havent tested it so watch your console for typeos :-)
function initBack(sel){
var s = sel||'a.goBackLink';
jQuery(s).each(function(){
var click = function(e){
// implementation for click
}
$(this).data('handler.click', click);
});
}
function enableBack(sel){
var s = sel||'a.goBackLink';
jQuery(this).each(function(){
var $this = jQuery(this);
if(typeof $this.data('handler.click') == 'function'){
$this.bind('goBack.click', $this.data('handler.click'));
$this.css("color", "lightGray ! important");
}
});
}
function disableBack(sel){
var s = sel||'a.goBackLink';
jQuery(s).each(function(){
var $this = jQuery(this);
$this.unbind('goBack.click');
$this.css("color", "#0000CC ! important");
});
}
jQuery(document).ready(function(){
initBack();
jQuery('#triggerElement').click(function(){
disableBack();
jQuery('#animatedElement').animate({/* ... */ }, function(){
enableBack();
});
});
});

Categories