Click events from two scripts on same element? - javascript

Edit: I think I got the solution! I want to try and fix this myself before I ask for further help = )
First script inhibits the second one from functioning as the click event from the first one overides the second one. Because the second one does not function it is impossible to open the drop down menu to select a list item to trigger the first scripts click.
What I tried was replacing all return false statements with event.stopPropagation(). Didnt work however. Tried re-ordering my scripts but that failed as well. I was thinking of making my second script target another parent div but that didnt work either.I also tried event.stopImmediatePropagation() and .bind methods.
Any idea?
First script that makes the drop down function. Contains click event.
function DropDown(el) {
this.f = el;
this.placeholder = this.f.children('span');
this.opts = this.f.find('ul.dropdown > li');
this.val = '';
this.index = -1;
this.initEvents();
}
DropDown.prototype = {
initEvents : function() {
var obj = this;
obj.f.on('click', function(event){
$(this).toggleClass('active');
return false;
});
obj.opts.on('click',function(){
var opt = $(this);
obj.val = opt.text();
obj.index = opt.index();
obj.placeholder.text(obj.val);
});
},
getValue : function() {
return this.val;
},
getIndex : function() {
return this.index;
}
}
$(function() {
var f = new DropDown( $('#f') );
$(document).click(function() {
// all dropdowns
$('.filter-buttons').removeClass('active');
});
});
Second script that does the filtering, also contains click event:
jQuery(document).ready(function(e) {
var t = $(".filter-container");
t.imagesLoaded(function() {
t.isotope({
itemSelector: "figure",
filter: "*",
resizable: false,
animationEngine: "jquery"
})
});
$(".filter-buttons a").click(function(evt) {
var n = $(this).parents(".filter-buttons");
n.find(".selected").removeClass("selected");
$(this).addClass("selected");
var r = $(this).attr("data-filter");
t.isotope({
filter: r
});
evt.preventDefault();
});
$(window).resize(function() {
var n = $(window).width();
t.isotope("reLayout")
}).trigger("resize")
});
html structure
<div id="f" class="filter-buttons" tabindex="1">
<span>Choose Genre</span>
<ul class="dropdown">
<li>All</li>
<li>Electronic</li>
<li>Popular</a></li>
</ul>
</div>

This doesn't really solve your problem but I was bored while drinking my coffee and felt like helping you write your dropdown plugin a little nicer
My comments below are inline with code. For uninterrupted code, see DropDown complete paste.
We start with your standard jQuery wrapper (function($){ ... })(jQuery)
(function($) {
// dropdown constructor
function DropDown($elem) {
First we'll make some private vars to store information. By using this.foo = ... we expose things (probably) unnecessarily. If you need access to these vars, you can always create functions to read them. This is much better encapsulation imo.
// private vars
var $placeholder = $elem.children("span");
var $opts = $elem.find("ul.dropdown > li")
var value = "";
var index = -1;
Now we'll define our event listeners and functions those event listeners might depend on. What's nice here is that these functions don't have to access everything via this.* or as you were writing obj.f.* etc.
// private functions
function onParentClick(event) {
$elem.toggleClass("active");
event.preventDefault();
}
function onChildClick(event) {
setValue($(this));
event.preventDefault();
}
function setValue($opt) {
value = $opt.text();
index = $opt.index();
$placeholder.text(value);
}
Here's some property descriptors to read the index and value
// properties for reading .index and .value
Object.defineProperty(this, "value", {
get: function() { return value; }
});
Object.defineProperty(this, "index", {
get: function() { return index; }
});
Lastly, let's track each instance of DropDown in an array so that the user doesn't have to define a special listener to deactivate each
// track each instance of
DropDown._instances.push(this);
}
This is the array we'll use to track instances
// store all instances in array
DropDown._instances = [];
This event listener deactivate each "registered" instance of DropDown
// deactivate all
DropDown.deactiveAll = function deactiveAll(event) {
$.each(DropDown._instances, function(idx, $elem) {
$elem.removeClass("active");
});
}
Here's the document listener defined right in the plugin! The user no longer has to set this up
// listener to deactiveAll dropdowns
$(document).click(DropDown.deactiveAll);
Might as well make it a jQuery plugin since everything in our DropDown constructor relies upon jQuery. This let's the user do var x = $("foo").dropdown();
// jQuery plugin
$.fn.dropdown = function dropdown() {
return new DropDown($(this));
};
Close the wrapper
})(jQuery);
Now here's how you use it
$(function() {
var x = $('#f').dropdown();
// get the value
f.value;
// get the index
f.index;
});
Anyway, yeah I know this doesn't really help you with your click listeners, but I hope this is still useful information to you. Off to the Post Office now!

I think you're going to need to simplify this to figure out what's going on. There's actually not enough information to see what elements the events are being attached to here.
For argument's sake, open the console and try the following:
$(document).on('click', function() { console.log('first'); return false; });
$(document).on('click', function() { console.log('second'); return false; });
Then click in the page. You'll see that both events are triggered. It might well be that your code is actually attaching the events to different elements (you don't say anywhere). If that's the case then you need to understand how event bubbling works in the DOM.
When you trigger an event, say a click on an element, that event will fire on that element, and then on it's parent, then grandparent etc all the way to the root node at the top.
You can change this behaviour by calling functions in the event itself. evt.stopPropagation tells the event to not bubble up to the ancestor nodes. evt.preventDefault tells the browser not to carry out the default behaviour for a node (eg, moving to the page specified in the href for an A tag).
In jQuery, return false from an event handler is a shortcut for, evt.preventDefault and evt.stopPropagation. So that will stop the event dead in its tracks.
I imagine you have something like:
<div event_two_on_here>
<a event_one_on_here>
</div>
If the thing that handles event_one_on_here calls stopPropagation then event_two_on_here will never even know it has happened. Calling stopPropagation explicitly, or implicitly (return false) will kill the event before it travels to the parent node/event handler.
UPDATE: In your case the issue is that the handler on .filter-buttons a is stopping the propagation (so #f doesn't get to run its handler).
$(".filter-buttons a").click(function(evt) {
// your code here...
// Don't do this - it stops the event from bubbling up to the #f div
// return false;
// instead, you'll probably just want to prevent the browser default
// behaviour so it doesn't jump to the top of the page ('url/#')
evt.preventDefault();
});

Related

jQuery - Bind two events to an AND operator

Is it posible to bind two events to an AND logic operator so that both has to be active for the function to be called? Say I have this:
foobar.bind("foo AND bar", barfunc);
function barfunc(e) {
alert("foobar!");
}
So in order for barfunc to be called both foo and bar needs to be active. This would be really useful cause I am making a slider/seeker out of divs (Cannot use jquery UI slider) and I need it to call the function when I am both pressing down my mouse button and hovering over the div.
It's not possible using syntax like that—the events will never fire at the exact same time, one will always be after the other. That said, you could do something like the following (pseudo code based off your example):
var isHovering = false,
isClicking = false;
function barfunc(e) {
if(isHovering && isClicking){
alert("foobar!");
}
}
foobar.on('mousedown', function(event){
isClicking = true;
barFunc(event);
}).on('mouseup', function(event){
isClicking = false;
}).on('mouseenter', function(event){
isHovering = true;
barFunc(event);
}).on('mouseleave', function(event){
isHovering = false;
});

2 anchor with one click

So here is my code
prev
prev
How do I make it both click if I click any of it ?
If I click .slider-1-prev, at the same I click .slider-2-prev
If I click .slider-2-prev, at the same I click .slider-2-prev
How to make it by javascript ?
As well as triggering the event on the other link, you need to shield against infinite repeating (e.g. with a shield variable):
var inClick = false;
$(document).ready(function {
$('.slider-1-prev').on('click', function {
if (!inClick) {
inClick = true;
$('.slider-2-prev').trigger('click');
inClick = false;
}
});
$('.slider-2-prev').on('click', function {
if (!inClick) {
inClick = true;
$('.slider-1-prev').trigger('click');
inClick = false;
}
});
})
If you want a shorter version, you can listen for both on one handler and click "the other":
var inClick = false;
$(document).ready(function {
var $sliders = $('.slider-1-prev,.slider-2-prev');
$sliders.on('click', function {
if (!inClick) {
inClick = true;
// Click the one that was not clicked (not this)
$sliders.not(this).trigger('click');
inClick = false;
}
});
})
Another option is a bit more complicated as you need to turn the handler off and then on again. Stick with this simple one for now.
The on/off approach involves disabling the handling while executing it, so that it will not trigger again until you reconnect it. The downside is you need to reference a separate function so that it can effectively reference itself:
$(document).ready(function {
var $sliders = $('.slider-1-prev,.slider-2-prev');
// Define separate named function
var clickTheOtherOne = function(){
// Disable the click
$sliders.off('click');
// Click the one that was not clicked (not this)
$sliders.not(this).trigger('click');
// Reenable the click handler
$sliders.on('click', clickTheOtherOne);
}
// Initial enabling of the handler
$sliders.on('click', clickTheOtherOne);
});
If they're going to behave the same, why not define only one function for both?
$('.slider-1-prev, .slider-2-prev').click(function(){
//... mutual code
});
I can't figure why you need to do what you ask, but try this approach:
js code:
// this will work on all classes that start with 'slider-prev'
$('*[class^="slider-prev"]').on('click',function{
// do something
});
Of course you will need to alter your htm code to:
prev
prev
this should do the trick
$(document).ready(function{
$('.slider-1-prev').on('click',function{
$('.slider-2-prev').trigger('click');
});
$('.slider-2-prev').on('click',function{
$('.slider-1-prev').trigger('click');
});
})
Try this -
$('.slider-1-prev').click(function(){
$('.slider-2-prev').trigger('click');
});
// If you need the opposite, then do -
$('.slider-2-prev').click(function(){
$('.slider-1-prev').trigger('click');
});

Call back from styled radio buttons

I am using the jQuery plugin radiosToSlider (http://rubentd.com/radios-to-slider/) and need to make sure that all radio button groups are checked and to give an alert when they are
I can do this if they are just radio buttons by checking the length but because the plugin changes the input buttons I am having difficulties
My fiddle is
http://jsfiddle.net/yFaAj/270/
$(document).ready(function () {
$(".radios").radiosToSlider();
});
$(":radio").change(function () {
var names = {};
$(':radio').each(function () {
names[$(this).attr('name')] = true;
});
var count = 0;
$.each(names, function () {
count++;
});
if ($(':radio:checked').length === count) {
alert("all answered");
}
}).change();
thanks
The problem isn't that the plugin changes your structure (although it does add some ins elements, which I don't agree with), it's that the plugin doesn't fire a change event for the converted radio controls, and setting the checked property interactively doesn't appear to do so either.
Since the plugin author doesn't publish an API for this use case, it's hard to know whether this is by design or oversight, but the source code definitely doesn't fire the event when the slider is clicked:
this.bearer.find('.slider-level').click( function(){
var radioId = $(this).attr('data-radio');
slider.bearer.find('#' + radioId).prop('checked', true);
slider.setSlider();
});
Your options, as I see them:
Contact the API author and ask for a bug fix, or the intended way to support this case
Downside: Time: dependent on the author to respond
Attach your "check" function to the click event of the .slider-level class, as the API does.
Downside: Brittle: future versions of the plugin may attach the behavior to different selectors
Attach your function to the click event of your radio group, and catch click events on the bubble
Downside: Inefficient: It will check for every click in the radio control
Here's a sample implementation of option 3. DEMO.
$(document).ready(function () {
$(".radios").radiosToSlider();
});
var makeIsRadioGroupChecked = function(selector) {
var $radioGroup = $(selector);
return function isRadioGroupChecked() {
return $radioGroup.find(':checked').length > 0;
};
};
var isOptionsChecked = makeIsRadioGroupChecked('#optionsRadioGroup');
var isSizeChecked = makeIsRadioGroupChecked('#sizeRadioGroup');
var areAllGroupsChecked = function() {
return isOptionsChecked() && isSizeChecked();
};
var alertIfAllGroupsChecked = function() {
if (areAllGroupsChecked()) {
alert("all answered");
}
};
$('.radios').on('click', alertIfAllGroupsChecked);

Javascript - Add specific keypress event inside a loop

I am attempting to assign a keypress event to an element within a for loop. I know that there are issues with assigning events while in a for loop dynamically, and I have solved that for the "click" event however I am at a loss for how it should work for the keypress. (probably because I don't really understand how the "click" one works to begin with... closure avoidance is not something I fully get)
The basic setup is that there is a for loop that will print out a number of different textareas and a div underneath them. Pressing the div will send the text in the text area to the right person. What I would like to have happen is that the same message should be sent if the enter button is pressed within the text area.
for( var i in people){
var message = $('<textarea></textarea>').appendTo(container);
message.on( "keypress", function(e) {
if(e.keyCode==13){
// code does make it in here ...
sendMessage(people[i].name); // but this never gets run
}
});
var messageButton= $('<div>Send</div>').appendTo(container);
messageButton.on( "click", sendMessage(people[i].name) );
}
var sendMessage = function(to) {
return function(){
/* do the sending of the message to the right person */
}
}
Can anyone help me understand the following?
Why does the click function work in the first place? I am not understanding why we have to put return around the function block.
Why doesn't the keypress function work similarly?
On a more general level, how does keypress work to begin with. The function(e) should not work because 'e' isn't anything, where does that even get set?
The problem with keypress in the code is that it will always send the message to latest person in people as at the moment when it is executed, i will have the latest value in it.
I probably would use forEach instead:
people.forEach(function (person) {
var message = $('<textarea></textarea>').appendTo(container);
// you can use keypress - http://api.jquery.com/keypress/#keypress-eventData-handler
// see the examples in the reference
message.keypress(function (e) {
if (e.which === 13) {
// here you should invoke the function returned by the sendMessage
sendMessage(person.name)();
}
});
var messageButton= $('<div>Send</div>').appendTo(container);
messageButton.click(sendMessage(person.name));
});
with this approach you do not need to wrap the function in the sendMessage and can just call the original function in the corresponding event handler.
Clean example using jQuery. You should read more about jQuery and closures for iterations so you can easily understand what is going on.
$.each(people, function (person) {
var $message = $('<textarea></textarea>').appendTo(container);
var $button = $('<div>Send</div>').appendTo(container);
var send = sendMessage(person.name);
// Keypress handler
$message.keypress(function (e) {
if (e.which === 13) { // on enter do the following
send();
}
});
$button.click(send);
});
Here's another solution using a handwritten closure:
http://jsfiddle.net/M5NsS/1/
var people = {
'p1': {
name: 'john'
},
'p2': {
name: 'bob'
},
'p3': {
name: 'jim'
}
};
var container = $('#container');
for (var i in people) {
(function (name) {
var message = $('<textarea></textarea>').appendTo(container);
message.keypress(function (e) {
if (e.keyCode == 13) {
sendMessage(name);
}
});
var messageButton = $('<div>Send</div>').appendTo(container);
messageButton.click(function () {
sendMessage(name)
});
})(people[i].name);
}
function sendMessage(to) {
console.log(to);
}
As others have stated, the issue is that the event is bound with the last reference to 'i' in the loop. Using a closure solves this issue while still allowing you to use your for..in loop.
Another thing to note is that if you are not dynamically appending these elements to the DOM after binding, there is no reason to use jquery's .on(). You can directly bind .keypress() and .click() handlers to the elements, as seen in my fiddle and on #AlexAtNet's answer.
But it's clunky, and I would just use jquerys $.each as others have already suggested.

JQuery - using .on with element insertion

I have a function which creates a tooltip for specific objects. Currently, I am running a tooltip function after ajax insertions to create and append the new tooltip objects. I am curious if there is a way to use .on() to auto-run the tooltip function on insertion, rather than manually running it.
For instance:
$('[title]').on('inserted', function(){
tooltip(this);
});
I did some reading and it looks like custom triggers might be the way to go, but I'd love if it something like this existed :)
Here's the pseudo code as per request.
$(document).ready(function() {
$('body').on('added','*',function() {
console.log($(this),'has been added');
});
$('body').append('<div>This is the first div</div>');
});
(function($) {
fncs = {
append:$.fn.append,
appendTo:$.fn.appendTo
// etc.
}
// we're assigning the original functions in this
// object to be executed (applied) later
$.fn.append = function() {
fncs.append.apply(this,arguments);
$(this).children().last().trigger('added');
return $(this);
}
$.fn.appendTo = function() {
fncs.appendTo.apply(this,arguments);
return $(this);
// no need to trigger because this function calls the one
// above for some reason, and it's taking care of the
// triggering the right element(s I think)
}
})(jQuery);
This is not the response you're looking for, but I would not attach tooltips directly on elements. Instead I would use a class for the ones I want the tooltip to show on mouseover and use the .on() event handler in the following way:
$('body').on('mouseover','.tooltip',function() {
// show tooltip
console.log($(this).data('tooltip'));
return false;
}).on('mouseout','.tooltip',function() {
// hide tooltip
return false;
});
So that whatever you add to the body (not necessarily as a direct child) will trigger this event handler.
I would probably just create an additional function to assign the tooltip data to each element along with the class.
$.fn.extend({
tooltip:function(text) {
text = text || '';
return $(this).each(function() {
$(this).data('tooltip',text).addClass('tooltip');
});
}
});
$('#someID').tooltip("Click me!");
$('button').tooltip("I'm a button");

Categories

Resources