Get ID of Element Being Clicked and Pass as Parameter? - javascript

How does one, through jQuery, get the ID of an element that is being clicked on and then pass it as a parameter into a function? Example jQuery code below.
jQuery(document).ready(function() {
var id = this_id;
jQuery(".lightbox a").click({param: id}, functionName);
});
May I note that the "param" parameter is integral to the structure of the function.
Apologies all, I am no Javascript master by any means.

I'm guessing the point is to pass event data to a function that expects that, as ,click() supports the .click( [eventData ], handler(eventObject) ) syntax, and if so, you have to iterate the collection yourself:
jQuery(document).ready(function($) {
$(".lightbox a").each(function() {
$(this).click({param: this.id}, functionName);
});
});
EDIT:
You could do this with on() as well:
jQuery(document).ready(function($) {
$(".lightbox a").each(function() {
$(this).on('click', {param: this.id}, functionName);
});
});
FIDDLE

Within the click handler, you can access the element ID with this.id or $(this).attr('id'):
jQuery(document).ready(function() {
jQuery(".lightbox a").click(function(){
functionName(this.id);
});
});

You can use this.id inside a click event, example:
jQuery(".lightbox a").click(function() {
var id = this.id;
//pass to a function
testFunction(id);
});
function testFunction(param) {
console.log(param);
}

It's easy just access to the this element to get the clicked element, then extract its id and save it into a variable like this:
jQuery(".lightbox a").click(function(){
var id = jQuery(this).attr("id");
callFunction(id);
});

http://jsfiddle.net/pArW6/
jQuery(document).ready(function() {
jQuery(".lightbox a").click(functionName);
});
function functionName()
{
alert(this.id);
}

You can you Use $(this).att("id").
$(".lightbox a").click(function() {
var ID=$(this).att("id");
//pass to a function
TestFunction(ID);
});
function TestFunction(P) {
console.log(P);
}
Live example
http://jsbin.com/enobop/1/edit

You can do this:
jQuery(document).ready(function () {
jQuery(".lightbox a").click(function (e) {
// Cancel the default action (navigation) of the click.
e.preventDefault();
// 'this' here refers to the link being clicked in the current scope
// you can check the console for the id for debug purpose
console.log(this.id);
// pass the id to the function
functionName(this.id);
});
});

Another way is to use the event parameter that gets passed to the callback function.
jQuery(".lightbox a").click(function(ev) {
console.log(ev.target.id);
}
Of course it's a mix of jQuery and pure JS.

Usually you have a function for an event declared with
function(event)
and the event has a target and the id of the target is, what you want. So
$("SomeElement").on("click", function(e){ callanotherFunction(e.target.id) })
does, what you wanted

You can use this.id or $(this).attr("id");, but you might want to get a reference to $(this) - wrapped or not - immediately and work from a variable if you do much of anything else in there.

Related

How to edit an event trigged by an anchor from inside of a $.get() function?

I'm trying to make a script that, when you click on an anchor, a $.get function will get the anchor's href and then the href will be removed, but I cannot edit anything about the anchor from inside de get element. Example:
// make anchor disappear for example (doesn't work)
$('.belovedanchor').click(function(e) {
$.get($(this).attr('href')).done(function() {
$(this).hide();
});
});
// make an anchor disappear using a function (doesn't work too)
$('.belovedanchor').click(function(e) {
function do() { $(this).hide(); };
$.get($(this).attr('href')).done(function() {
do();
});
});
I don't understand why $(this) change to work with the $.get function istead of the .click event.
How would you guys do it?
You have a couple problems. Edit: Only one problem -- I now see from your comment below that belovedanchor is not the actual selector in your code.
First, your jQuery selector for the click event handler is most likely incorrect. Change $('belovedanchor') to $('.belovedanchor') or $('#belovedanchor') depending if the anchor is identifiable by either class or element ID respectively.
Second, this in the do callback function does not refer to the anchor. In JavaScript, scope is set at the function level, so anytime you declare a new function, this will refer to that new scope.
Do this instead:
$('belovedanchor').click(function(e) {
var anchor = $(this);
function do() { anchor.hide(); };
$.get($(this).attr('href')).done(function() {
do();
});
});
Simplified:
$('belovedanchor').click(function(e) {
var anchor = $(this);
$.get(anchor.attr('href')).done(function() {
anchor.hide();
});
});
This may work properly
$('.belovedanchor').click(function() {
var selectedancor = $(this);
var myurl = $(this).attr('href');
$.get(myurl, function() {
selectedanchor.hide();
});
});

Confused with calling JQuery custom function

I have html like so
<span rel='comm' val='12'>click</span>
<span rel='comm' val='82'>click</span>
and I am using JQuery to do this
$('span[rel*=comm]').cust();
and the custom function is as such
$.fn.cust = function () {
$(this).click(function(e) {
alert($(this).val());
});
}
The value of this is 12 even when I click on 2nd span which should give me 82
Any help would be appreciated.
You'll need to return a seperate function for each element in the collection, normally done with return this.each ...
$.fn.cust = function () {
return this.each(function() {
$(this).click(function(e){
alert($(this).val());
});
});
}
And value is not a valid attribute for a span element.
This should work better:
$.fn.cust = function () {
$(this).click(function (e) {
alert($(this).attr('val'));
});
}
span does not have value.
http://jsfiddle.net/dREj6/
Also if you want to make your method chainable you should return an jQuery instance:
$.fn.cust = function () {
return $(this).click(function (e) {
alert($(this).attr('val'));
});
}
$('span[rel*=comm]').cust().css('color', 'red');
http://jsfiddle.net/dREj6/1/
rel are for links (anchor element) - use class
use data attribute instead of custom attributes
http://jsbin.com/ogenev/1/edit
<span class='comm' data-val='12'>click</span>
<span class='comm' data-val='82'>click</span>
$.fn.cust = function(){
$(this).click(function(){
alert(this.dataset.val);
});
};
$('.comm').cust();
It works if you use .attr('val')
$.fn.cust = function () {
$(this).click(function(e){
alert($(this).attr('val'));
});
}
$('span[rel*=comm]').cust();
http://jsfiddle.net/fW7FT/
.val() is for input since they're the only one accepting the val attribute officialy
The call $('span[rel*=comm]') returns a JQuery wrapper for all spans matching the selector - the two ones you have in your example are picked both.
Now inside the definition of cust, $(this) refers to the wrapped array, which causes your issue. Use
$(this).each( function() {
$(this).click (...
});
Inisde each $(this) will point to each separate span element in the selection, so they will have the click handler individually attached and working as you expect.
You can achieve what you're looking for with this:
HTML:
<span rel='comm' val='12'>click</span>
<span rel='comm' val='82'>click</span>
JS:
var cust = function(source) {
alert($(source).attr('val'));
}
$('span[rel*=comm]').click(function(e) {
cust(this);
});
The JSFiddle working: http://jsfiddle.net/ejquB/

Hooking events with .on() with JQUERY

I want to hook events with the .on() method. The problem is I don't know how to get the object reference of the element on which the event take place. Maybe it's a midunderstanding of how the method really works... but I hope you can help.
Here's what I want to do:
When a file is selected, I want the path to be displayed in a div
<div class="wrapper">
<input type="file" class="finput" />
<div class="fpath">No file!</div>
</div>
Here's my script
$(document).ready(function() {
$this = $(this);
$this.on("change", ".finput", {}, function() {
var path = $(this).val()
$(this).parents().children(".fpath").html(path.split("\\").pop());
});
});
Something like that but that way it doesn't work.
Like this
$(document).ready(function() {
$('.finput').on("change", function() {
var path = $(this).val()
$(this).parents().children(".fpath").html(path.split("\\").pop());
});
});
Do you need to use on()? I'm not sure what you are trying to do exactly.
$("#wrapper").on("change", ".finput", function(event){
var path = $(this).val()
$(this).parents().children(".fpath").html(path.split("\\").pop());
});
I haven't tested your code, but you need to attach the on() to the wrapper.
Can you just use change()?
$('.finput').change(function() {
var path = $(this).val()
$(this).parents().children(".fpath").html(path.split("\\").pop());
});
This should help. If you want to see when a file input changes, bind the event to it
$("input[type='file']").on("change", function(e){
var path = $(this).val();
})
Try:
$(document).ready(function() {
$('body').on('change','input.finput', function() {
var path = $(this).val()
$(this).parent().children(".fpath").html(path.split("\\").pop());
});
});
$(document).on("change", ".finput", function() {
$(".fpath").html(this.value.split("\\").pop());
});
This is a delegated event handler, meaning the .finput element has been inserted dynamically so we need to delegate the listening to a parent element.
If the .finput element is not inserted with Ajax and is present on page load, you should use something like this instead:
$(".finput").on("change", function() {
$(".fpath").html(this.value.split("\\").pop());
});

How to get the click event values outside the function in jQuery

How can I get the onclick event (this value change when click on div) in jQuery?
$("ul li").click(function(){
var v = $(this).val();
});
$(function(){
alert(v);
});
$(function() {
var v;
$('ul li').click(function() {
v = $(this).val(); // .text() - consider
testFunction();
});
function testFunction() {
alert(v);
}
});
Your issue was variable scope, you were defining a variable only available to the click function. If you define it outside of the function it will be available to other in scope functions.
Here's a demo:
http://jsfiddle.net/vs87B/
You might want to consider using .text() instead of .val()
If what you mean getting the innerHTML of the div when clicked, here is a code that could help
$("div").click(function(){console.log($(this).html())})
as I understand that you want to change the text of a div
your div is as follow
<div>123</div>
you can do it as
<script>
$("div").click(function () {
$(this).replaceWith( "new text " );
});
</script>
EDIT
you can use global variable as follow
$.mynamespace = {};
$("ul li").click(function(){
$.mynamespace.myVar = $(this).val();
});
$(function(){
alert( $.mynamespace.myVar );
});
refer How to store a global value (not necessarily a global variable) in jQuery?

Jquery dynamically create link

I have a piece of JQuery that creates a row in a table and in one of the cells there is an X that is surrounded by a class. When it is dynamically created and then clicked on the click listener does not fire.
Here is the code.
$('#add').click(function() {
$( '#table' ).append('<td class="x">X</td></tr>');
});
$('.x').click(function() {
alert('Fired');
});
Since the <td> element does not yet exist when you register your event handler, you have to use live() or delegate() for the handler to be triggered later:
$(".x").live("click", function() {
alert("Fired");
});
$(".x").live("click", function()
{
alert("Fired");
});
Live adds events to anything added later in the DOM as well as what's currently there.
Instead of
$('.x').click(function() {
alert('Fired');
});
Change to this
$('.x').live('click', function() {
alert('Fired');
});
It binds the click function to any created element with class x
You need to use the .live function for content that's dynamically generated.
so replace
$('.x').click(function() {
with
$('.x').live('click',function() {
You are first creating the listener to all .x elements (of which there are presumably zero), then later adding new .x elements.
There are two solutions: one is to use jQuery live, the other is to rewrite your code:
var xClickHandler = function() {
alert('Fired');
};
$('#add').click(function() {
$('#table').append(
$('<td class="x">X</td></tr>').click(xClickHandler);
);
});
Use live instead of click:
$('.x').live("click", function() {
alert('Fired');
});
The html you are appending to the table has a typo, you have missed out the beggining tr tag:
$('#add').click(function() {
$( '#table' ).append('<tr><td class="x">X</td></tr>');
});
$('.x').click(function() {
alert('Fired');
});
I think you need to use the live method. http://api.jquery.com/live/
$('.x').live('click', function() {
// Live handler called.
});

Categories