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

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?

Related

jQuery not executing code for new element with new id

I have an image, and when I click on it I want it to change to a different image and change its ID as well. Then when I click on this new image, it reverts back.
$(document).ready(function(){
$("#name_edit").click(function(){
$(this).attr("src", "img/tick.png");
$(this).attr("id","name_confirm");
});
$("#name_confirm").click(function(){
$(this).attr("src", "img/edit.png");
$(this).attr("id","name_edit");
});
});
I have successfully done the first step, going from #name_edit to #name_confirm. However, not the reverse.
How do I go about solving this?
My suspicion is that since I'm using (document).ready, jQuery is preparing itself for elements already on the page. However, the element with the ID name_confirm does not exist until the image is clicked on.
Thanks.
The element that you are working on is always the same...
$(document).ready(function(){
// use just the first id value to find it in the DOM
$("#name_edit").click(function(){
var item = $(this);
var id = item.attr('id');
if(id === 'name_edit') {
return item
.attr("src", "img/tick.png")
.attr("id","name_confirm")
;
}
return item
.attr("src", "img/edit.png")
.attr("id","name_edit")
;
})
;
});
I think you have chosen bad solution for your problem.
1) Why your code doesn't work:
You bind 2 events only 1 time, whne your document loaded. So, jquery finds #name_edit element and bind onclick event on it. But jquery cannot find #name_confirm element, because it doesn't exists on document ready)
In your code you should bind 1 onclick event, but have some attr (for example class for checking your state).
Something like:
<img id="main_image" class="name_edit"/>
<script>
var img_paths = ["img/tick.png", "img/edit.png"]
var img_index = 0;
$("#main_image").click(function(){
if($(this).attr("class") == "name_edit"){
$(this).attr("src", "img/tick.png");
$(this).attr("class","name_confirm");
}
else{
$(this).attr("src", "img/edit.png");
$(this).attr("class","name_edit");
}
});
</script>
Other solutions: You can create 2 images and show/hide them.
Or use styles with background attr. With pseudoclasses or classes.
Also you can store image pathes in array and tick array index on click.
Something like:
var img_paths = ["/content/img1.png", "/content/img2.png"]
var img_index = 0;
$("#main_image").click(function(){
$(this).src = img_paths[img_index];
img_index = !img_index;
})
It is not working because you are referencing the same elements, try this:
(function(window, document, $, undefined){
$("#name_edit").on("click", function(){
var self = $(this);
if(self.attr("id") === "name_edit") {
self.attr("src", "img/tick.png");
self.attr("id", "name_confirm");
} else {
self.attr("src", "img/edit.png");
self.attr("id", "name_edit");
}
});
})(this, this.document, jQuery);
Also for easier to understand code you could use classes like this:
(function(window, document, $, undefined){
$(".name_edit").on("click", function(){
var self = $(this);
if(self.hasClass("name_edit")) {
self.attr("src", "img/tick.png");
self.removeClass("name_edit").addClass("name_confirm");
} else {
self.attr("src", "img/edit.png");
self.removeClass("name_confirm").addClass("name_edit");
}
});
})(this, this.document, jQuery);
To simplify replacing classes you could even add your own $.fn.replaceClass(); like this:
jQuery.fn.replaceClass = function(classA, classB) {
this.removeClass(classA).addClass(classB);
return this;
};
Then use it like this:
(function(window, document, $, undefined){
$(".name_edit").on("click", function(){
var self = $(this);
if(self.hasClass("name_edit")) {
self.attr("src", "img/tick.png");
self.replaceClass("name_edit", "name_confirm");
} else {
self.attr("src", "img/edit.png");
self.replaceClass("name_confirm", "name_edit");
}
});
})(this, this.document, jQuery);
I can confirm what the others said.. the jquery gets run on document ready, but doesn't get updated subsequently - so it basically gets the correct element from the dom, and assigns the click event. It has no event for the name_confirm.
so this code does nothing...
$("#name_confirm").click(function(){
$(this).attr("src", "img/edit.png");
$(this).attr("id","name_edit");
});
See it not work in this instructive jsfiddle
Of course does the id need to change? is it possible to use for example a specific class for the img? then you could make the second click bind on the class instead... for example see this working example, which still changes the src and id...
Try On method:
$(document).on('click', '#name_edit', function(){
$(this).attr("src", "img/tick.png");
$(this).attr("id","name_confirm");
});
$(document).on('click', '#name_confirm', function(){
$(this).attr("src", "img/edit.png");
$(this).attr("id","name_edit");
});

Get element by ID using class name

I want get the id of the element that is clicked and within a specified class, and want to print the ID.
Here is my JS , I am really new JS , Please help
$('.wrapinner').click(function(e) {
$('.wrapinner').css("margin-top","0");
$('.wrapinner').css("opacity","0.4");
$(this).css("margin-top","25px");
$(this).css("opacity","1");
var r= document.getElementById(this).attributes.toString();
document.write(r);
});
There are two ways to do this:
1) Done without jQuery object (it is faster)
$(".wrapinner").click(function(){
//Your Code
var id = this.id;
document.write(id);
});
OR
2) Done with jQuery object:
$(".wrapinner").click(function(){
//Your Code
var id = $(this).attr('id');
document.write(id);
});
NOTE after jfriend00's comment.
Use document.write() if really needed and is not harmful to your page OR use console.log(). Read Why is document.write considered a "bad practice"?
You can call the native javascript object directly; this.id.
$('.wrapinner').click(function(e) {
$('.wrapinner').css("margin-top","0").css("opacity","0.4"); // chained these two
$(this).css("margin-top","25px").css("opacity","1"); // chained these two
var r = this.id; // this should already reference the correct element.
document.write(r);
});
Try this way :
$('.wrapinner').click(function(e) {
console.log(this.id);
});
You are not passing id to getElementById, rather you are passing the object it self. You can get id of source object of event using this.id not by this.
Change
var r= document.getElementById(this).attributes.toString();
To
var r= document.getElementById(this.id).attributes.toString();
Just write
document.write(this.id)
$(".wrapinner").click(function(){
var id = this.id
});
Try this example:
<table>
<tbody>
<tr id="CustomerScreen" class="rows"></tr>
<tr id="TraderScreen" class="rows"></tr>
<tr id="DistributorScreen" class="rows"></tr>
</tbody>
</table>
<script>
$('.rows').each(function () {
var ar = this.id;
console.log(ar);
});
</script>
You can check this code..
$('.wrapinner').click(function(e) {
var getID = $(this).attr('id');
alert(getID);
});
Try this:
$('.wrapinner').click(function(e) {
$('.wrapinner').css("margin-top","0");
$('.wrapinner').css("opacity","0.4");
$(this).css("margin-top","25px");
$(this).css("opacity","1");
var id = $(this).attr('id');
});
I am capturing click event on class and then finding its id and class name using parent().
demodemo
$(document).ready(function(){
$('.class-first ul li, .class-second ul li, .class-third ul li').on('click',function(){
console.log("child :"+$(this).attr('id') + " Parent:"+$(this).parents().eq(1).attr('class'));
});
})

jQuery Change Color on click

I am a jQuery beginner and want to achieve the following - whenever I click on any element of the page, I want the color of the text inside it to be changed to red. This is what I have but it doesn't work. Surprisingly the alert statement also prints nothing. But it does executes as I tested it with another alert statement. Thanks.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<div>Cow</div>
<div>Cat</div>
<p>paragraph</p>
<p>coconut</p>
<script type="text/javascript" src="../Scripts/jquery-2.0.3.js"></script>
<script type="text/javascript">
$(this).click(function () {
var v = $(this).text();
alert(v); // this prints nothing !!!!
$(this).css("color", "red");
});
</script>
</body>
If you attach the click handler to the document, any click that bubbles up to the document will go to the event listener. If you now within the listener look for the event.target, that will be the node that initiated the event:
$(document).click(function (event) {
$(event.target).css("color", "red");
});
example: http://jsfiddle.net/E9H22/
If you specify the body element (in place of this), then it works:
$('body').click(function () {
var v = $(this).text();
alert(v); // this prints something, now.
$(this).css("color", "red");
});
JS Fiddle demo.
You could also, of course, use:
$(this.document.body).click(function () {
var v = $(this).text();
alert(v); // this prints something, now.
$(this).css("color", "red");
});
JS Fiddle demo.
If you want only the clicked-element to have its text turn red:
$('body').click(function (e) {
$(e.target).css("color", "red");
});
JS Fiddle demo.
$(this).click(function () {
This is your problem.
Instead of saying this, you need to use CSS selectors to specify which elements will change color.
For example, you could try
$('div').click(function() { // Will change the color of the divs
var v = $(this).text();
alert(v); // this prints nothing !!!!
$(this).css("color", "red");
});
$('p').click(function() { // Will change the paragraphs
...
});
$('p, div').click(function() { // Will work for either one!
...
});
$('*').click(function() { // Will work for any element on the page
...
});
In your
$(this).click(function () {
"this" doesn't refer to where the <script> tag is located, but rather it refers to window object. So in essence your code does this:
$(window).click(function (){
If you want the cow to turn red, when clicking it, change HTML to:
<div id="cow">Cow</div>
And your script:
// callback needs to be inside $(document).ready(fn) to make sure the DOM is ready when trying to use it
$(document).ready(function () {
// and we need to refer to an explicit element
$('#cow').click(function (){
// now we can refer to "this", since inside the click handler's context is the clicked element
$(this).css({color: 'red'});
});
}
You must specify to which element you wanna add a click event. E.g. this will work for all the div-elements:
$('div').click(function () {
$(this).css("color", "red");
});
You need to wrap that in a document ready statement, and attach the click listener to an actual element:
$(function(){
$("*").click(function () {
$(this).css("color", "red");
});
});
Your selector could look something like $("div, p").click(...) depending on which elements you want to be active.

Get ID of Element Being Clicked and Pass as Parameter?

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.

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/

Categories