Match event.target with existing jQuery object - javascript

How can I do that?
event.target returns a HTML object,
and my element is a jQuery object.
Is there a better way to find out if event.target = my_jquery_object, besides comparing IDs or classes?
I want to make sure that it's the same object, not just a element with a similar class...
I tried with $(event.target) !== the_element and it fails
the_element is defined at the begining as $('.something', $(this))
What I am trying to do is to make a box close when the user clicks outside of it, but with the condition that the click wasn't made on the link that opened the box in the first place.
So I have this:
$(document).click(function(event){
if(($(event.target).parents().index(box) == -1)
&& box.is(':visible')){
close();
}
});
And I want to add another condition that verifies that the click wasn't made on the link that opened the box.
This works, but I don't like it:
if($(event.target).attr('id') != the_element)
:)

You can get the actual DOM element from the jQuery using .get(0) or simply the_element[0]. It would probably be better to check with jQuery, though.
if (the_element.is(event.target))
{
...
}
Using your example:
$(document).click(function(event){
if (the_element.is(event.target)) {
return false;
}
if(($(event.target).parents().index(box) == -1)
&& box.is(':visible')){
close();
}
});

Try -
if(event.target === the_element[0])
the_element[0] should unwrap your jQuery object and return a 'normal' DOM object, you can then compare it against the DOM object returned by event.target.

Maybe I'm wrong, but it looks like nobody understood the question?... I also want to know how to GET JQUERY OBJECT on which I used listener function from the EVENT.TARGET, but not a DOM node for a jquery object!!))
So... I found not a very handy, but working solution:
var elem = $('<input type="text" class="input" />');
elem.focus( $.proxy( function( e )
{
this.onInpFocus( e, elem );
}, this ) );
And modified the listener's callback method to receive 2 arguments:
onInpFocus : function( e, inp )
Instead of using simple way like:
elem.focus( $.proxy( this.onInpFocus, this ) );

Actually, I found another way, much more handy one :)
Just need to use the data argument:
Data to be passed to the handler in event.data when an event is
triggered.
Now my code looks like this:
var inp = $('<input type="text" />');
inp.focus( { j : inp } , $.proxy( this.onInpFocus, this ) );
//and the handler method
onInpFocus : function( e )
{
var inp = e.data.j;
...
}

Related

Embed javascript function within another javascript function

I have a form with a conditional field that is only shown if the user selects a radio button for "other." If I remove the conditional on this field, my original javascript function works; however, with the conditional I can not get it to fire correctly.
The form has an event "cf.add" that fires when a conditional field is made visible, and using this jquery I get a correct response in the console:
jQuery( document ).on( 'cf.add', function(){
console.log('cf.add triggered' );
});
And if I remove the conditional so that this field is rendered when the page is rendered, I get the correct response in this field, which is to add a '$':
$("#fld_3169487_4").on("blur", handleChange);
function handleChange() {
var myValue = document.getElementById("fld_3169487_4").value;
if (myValue.indexOf("$") != 0)
{
myValue = "$" + myValue;
}
document.getElementById("fld_3169487_4").value = myValue;
}
I've tried putting this second function within the first, but no luck. I feel like I'm adding them in the incorrect order when I try to combine the two, I'm not sure what I'm doing wrong though.
I've also tried to call the function handleChange() on the 'cf.add' trigger, but that did not work for me either.
After some playing around, I figured it out:
jQuery( document ).on( 'cf.add', function(){
var otherField = $("#fld_3169487_3");
otherField.focus();
var dollarValue;
$(otherField).on("blur", function() {
dollarValue = otherField.val();
if (dollarValue.indexOf("$") != 0) {
dollarValue = "$ " + dollarValue;
}
$(otherField).val(dollarValue);
});
});
Since cf.add is an custom even that is published by your form, you can have other elements subscribe to the event:
$("#fld_3169487_4").on('cf.add', function(event){
if ($(this).val().indexOf("$") != 0)
{
$(this).val("$" + $(this).val());
}
});
Using $(this), we can target just the field the event is attached to. Additionally, data from the event publisher can be passed to the subscribers via the event argument.

Javascript - Function to use onclick?

I want to create a function and then use with onclick method, for example:
one = document.getElementById("oneID");
then instead of writing function for each onclick():
one.onclick = function(x) {
tempStack.push(parseFloat(one.value));
viewTemp.value += one.value;
}
I want to use a single function:
one.click = input(one);
but I'm not sure how to do it in the correct way for example the below I tried, doesn't work:
var input = function(x) {
tempStack.push(parseFloat(x.value));
viewTemp.value += x.value;
}
Lastly, no external JavaScript libraries to aid this question, vanilla JavaScript.
You'll need to pass a function as a reference, not call it:
one.onclick = input;
In this case you won't be able to pass an argument, but you can use this as a reference for the DOM element on which event is fired:
function input() {
tempStack.push(parseFloat(this.value));
viewTemp.value += this.value;
}
Here's a method with using JavaScript's .addEventListener(), as a previous answer mentioned, using this to pass through the DOM Node Element to use within the inputFunction.
<input type="text" value="64.23" id="bt" />
<script>
function inputFunction( x ) {
console.log( x.value ); //Console Logs 64.23
}
var bt = document.getElementById("bt");
bt.addEventListener( 'click', function(){ inputFunction( this )}, false );
</script>
Fiddle: http://jsfiddle.net/Lhq6t/
Think about functions as a normal objects, so the way is:
function input (event) {
// Process the event...
// event is my event object
// this is the object which trigger the event
// event.target is my button
}
on.onclick = input;
You must assign the input function as a normal variable.
The function input will receive an event object as parameter. Also you can refer to the button clicked with this.
Maybe the mozilla developer network or the real w3c site would explain it better.
Your requirement can be achieved by following:
Add this method in your script tag:
function input(x) {
/*tempStack.push(parseFloat(x.value));
viewTemp.value += x.value;*/
alert(x.id);
}
And then call this method onClick event of your buttons / anchors like:
<input type="button" id="oneID" value="oneID" onClick="input(this);"/>
<input type="button" id="twoID" value="twoID" onClick="input(this);"/>
threeID
See working example: http://jsfiddle.net/Avd5U/1/
ok, so just create a function with a parameter in it like:
function setValue(input){
tempStack.push(parseFloat(input.value));
viewTemp.value += input.value;
}
and then call the function on the click of that element like:
var one = document.getElementById("oneID");
one.click = setValue(one);
Good luck!

Javascript Iteration issue

I am trying to iterate over the following Code and for some reason each time i iterate over it, it fires off the event handler, does any one know why it would be automatically firing off the handler?
nmbr = 1;
x1 = document.getElementsByClassName('fp')[0] ;
slowSkrol = document.createElement('button');
slowSkrol.className = 'mods';
slowSkrol.value= nmbr;
x1.appendChild(slowSkrol);
slowSkrol.addEventListener('click', whenclicked(nmbr),false);
function whenclicked(vv){
alert(vv);
}
You are calling the function, and binding it's return value to the event, rather than binding the function itself to the event. Replace whenclicked(nmbr) with:
function(){ whenclicked(nmbr); }
In modern browsers you could also use bind:
whenclicked.bind(null, nmbr);
change:
slowSkrol.addEventListener('click', whenclicked(nmbr),false);
to
slowSkrol.addEventListener('click', function() {
whenclicked(nmbr);
},false);
I shouldn't be adding another answer really. but the correct way to do this so that you get all arguments and the this would be like so.
slowSkrol.addEventListener('click', function( event ) {
whenclicked.apply(this, [event, nmbr]);
}, false);
Then you can use it like so.
function whenclicked( event, nmbr ){
alert(this, event, nmbr);
// this = slowSkrol
}

How Store and Disable Event of another element Temporary

I am looking for a way to manage the events. I have a hover function for element A, and click function for element B. I want to disable A`s hover function temporary while the second click of B.
I am looking for a way that not necessary to rewrite the hole function of A inside of B. Something very simply just like "Store and Disable Event, Call Stored Function"
I found some technique like .data('events') and console.log. I tired but failed, or maybe I wrote them in a wrong way.
Please help and advice!
$(A).hover();
$(b).click(
if($.hasData($(A)[0])){ // if A has event,
//STORE all the event A has, and disable
}else{
//ENABLE the stored event for A
}
);
Try this
var hoverme = function() {
alert('Hover Event Fired');
};
$('.A').hover(hoverme);
var i = 0;
$('.B').on('click', function(){
if(i%2 === 0){
// Unbind event
$('.A').off('hover');
}
else{
// Else bind the event
$('.A').hover(hoverme);
}
i++;
});
Check Fiddle
I think that what you want to do is something like this (example for JQuery 1.7.2):
$("#a").hover(function(){alert("test")});
$("#a")[0].active=true;
$("#b").click(function(){
if($("#a")[0].active){
$("#a")[0].storedEvents = [];
var hoverEvents = $("#a").data("events").mouseover;
jQuery.each(hoverEvents , function(key,handlerObj) {
$("#a")[0].storedEvents.push(handlerObj.handler);
});
$("#a").off('hover');
}else{
for(var i=0;i<$("#a")[0].storedEvents.length;i++){
$("#a").hover($("#a")[0].storedEvents[i]);
}
}
$("#a")[0].active = ($("#a")[0].active)==false;
});​
JSFiddle Example
But there are a couple of things that you must have in consideration:
This will only work if you add the events with JQuery, because JQuery keeps an internal track of the event handlers that have been added.
Each version of JQuery handles data("events") differently, that means that this code may not work with other version of JQuery.
I hope that this helps.
EDIT:
data("events") was an internal undocumented data structure used in JQuery 1.6 and JQUery 1.7, but it has been removed in JQuery 1.8. So in JQuery 1.8 the only way to access the events data is through: $._data(element, "events"). But keep in mind the advice from the JQuery documentation: this is not a supported public interface; the actual data structures may change incompatibly from version to version.
You could try having a variable that is outside the scope of functions a and b, and use that variable to trigger the action to take in function b on function a.
var state;
var a = function() {
if(!state) {
state = true;
// Add hover action and other prep. I'd create a third function to handle this.
console.log(state);
};
var b = function() {
if(state) {
state = false;
// Do unbinding of hover code with third function.
} else {
state = true;
// Do whatever else you needed to do
}
}
Without knowing more about what you're trying to do, I'd try something similar to this.
It sounds like you want to disable the click hover event for A if B is clicked.
$("body").on("hover", "#a", function(){
alert("hovering");
});
$("#b").click( function(){
$("body").off("hover", "#a", function() {
alert("removed hovering");
});
});
You can use the jQuery off method, have a look at this fiddle. http://jsfiddle.net/nKLwK/1/
Define a function to assign to hover on A element, so in b click, call unbind('hover') for A element and in second click on b element define again a function to hover, like this:
function aHover(eventObject) {
// Todo when the mouse enter object. You can use $(this) here
}
function aHoverOut(eventObject) {
// Todo when the mouse leave the object. You can use $(this) here
}
$(A).hover(aHover, aHoverOut);
// ...
$(b).click(function(eventObject) {
if($.hasData($(A)[0])){ // if A has event,
$(A).unbind('mouseenter mouseleave'); // This is because not a event hover, jQuery convert the element.hover(hoverIn, hoverOut) in element.bind('mouseenter', hoverIn) and element.bind('mouseleave', hoverOut)
}else{
$(A).hover(aHover, aHoverOut);
}
});
There are provably better ways to do it, but this works fine, on document ready do this:
$("#a")[0].active=false;
$("#b").click(function(){
$("#a")[0].active = ($("#a")[0].active)==false;
if($("#a")[0].active){
$("#a").hover(function(){alert("test")});
}else{
$("#a").off('hover');
}
});
JSFiddle example
You can use .off function from jQuery to unbind the hover on your "a" element.
function hoverA() {
alert('I\'m on hover');
}
$('#a').hover( hoverA );
var active = true;
$('#b').on('click', function(){
if(active){
$('#a').off('hover');
active = false;
} else{
$('#a').hover(hoverA);
active = true;
}
});
Live demo available here : http://codepen.io/joe/pen/wblpC

Find parent element in JQuery event

I've added a click event as follows and would like to check if the target has a specific parent.
$(document).click(function(event){
// Check here if target has specific parent for example -> #parent
});
How can this be done?
There's a .parent() dom traversal method for this.
according to Pointy's crystal ball, you probably want to do something like this:
$(document).click(function(event) {
if ($(event.target).parents('.selector').length > 0) {
}
});
I'm not sure why are you set click handler on document, maybe looking for event delegation and the .on()?
I believe this also works.. AFAIK jQuery events use the the literal element instead of a jQuery object when calling events. Basically this should be your normal DOM element with normal JavaScript properties.
$(document).click(function(event)
{
let myparent = $(this.parentNode); //jquery obj
let parent = $(this.parentNode)[0]; //plain DOM obj
let myself = $(this); //jquery obj;
let $elf = this; //plain DOM obj
});
Note: sometimes using 'self' as a variable is bad/causes conflicts with certain libraries so i used $elf. The $ in $elf is not special; not a jQuery convention or anything like that.
$(document).click(function(event){
var $parent = $(this).parent();
// test parent examples
if($parent.hasClass('someclass')) { // do something }
if($parent.prop('id') == 'someid')) { // do something }
// or checking if this is a decendant of any parent
var $closest = $(this).closest('someclass');
if($closest.length > 0 ) { // do something }
$closest = $(this).closest('#someid');
if($closest.length > 0 ) { // do something }
});
I have reliably used this in the past:
var target = $( event.target )
This will give you a reference to the jQuery object for the element that had the event invoked. You could use this same approach and see if the parent is "#parent", something like this:
var target = $( event.target )
if (target.parent().attr('id') == "#parent") {
//do something
}

Categories