this reference in JavaScript - javascript

Today i was writing some basic stuff of java script mean while i encountered the problem. Although i was able to sort out the problem but could not find the reason of why this were not working. Here is my code
$('document').ready(function() {
$(this).click(function() {
var node1 = $(this);
a = node1.text();
console.log(a);
});
});
In this in the console i see empty string. But if i change the $(this).click(function{...}) to $('.some_class_name').click(function{.....}); than my code works fine and display the text value of the button i clicked.
I want to know what is wrong in the above code.

You must be looking for this, Use the e.target to get the text inside of the clicked element which is present inside the document.
$('document').ready(function () {
$(this).click(function (e) {
var node1 = $(e.target);
var a = node1.text();
console.log(a);
});
});

Try this code
Just change the this keyword to body
<script type="text/javascript" src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<script type="text/javascript">
$('document').ready(function(){
$('body').click(function(){
var node1 = $(this);
a = node1.text();
console.log(a);
});
});
</script>
<body>
Test
</body>

Related

Onclick get element id result undefined jquery

I know this will mark as duplicate.. but i already try looking other post even i ask Mr. Google but i totally confuse.. i try use every sample on post but seems not all work..
What i'm trying to archive is.. when i click button jquery will show button id on alert popup. But i always got result undefined.
Here my sample code
PHP
<button class="myButton" name="testResultByName" data-value="testResultByDataValue" id="testResultByID">Click</button>
JQUERY and i put this code right before closing body </body> tag and already try on top right before closing head </head> tag
<script type="text/javascript">
$('.myButton').click(function(event){
var myButtonVar = $(this).prop('data-value');
alert(myButtonVar);
event.preventDefault();
});
</script>
I already try to use
$(this).prop('id');
$(this).prop('name');
$('.myButton').attr('data-value');
$('.myButton').attr('id');
$('.myButton').attr('name');
nothing work.. but if i use class like below it's work...
$('.myButton').prop('class');
then alert show class name "myButton" seems work.. i already use external jquery file too.. but nothing work.. already use ready() too but result still same..
did i miss something? oh and i use jquery-1.11.3.js
You $.data instead of .prop, like so
$('.myButton').click(function(event){
var myButtonVar = $(this).data('value');
var buttonId = $(this).attr('id');
console.log(myButtonVar);
console.log(buttonId);
});
Example
You get the value from the attr().
Please see the example code for the same
$(document).ready(function(){
$('.myButton').click(function(event){
var myButtonVar = $(this).attr('data-value');
alert("data-value = "+myButtonVar);
myButtonVar = $(this).attr('id');
alert("id = "+myButtonVar);
myButtonVar = $(this).attr('name');
alert("name = "+myButtonVar);
myButtonVar = $(this).attr('class');
alert("class = "+myButtonVar);
event.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="myButton" name="testResultByName" data-value="testResultByDataValue" id="testResultByID">Deposit</button>
Try this:
$('.myButton').on('click', function(){
var btnValue = $(this).attr('data-value');
alert(btnValue);
return false;
});

get the href value by clicking on anchor in multiple anchors using jquery

i'm trying to get the href value in multiple links or tag a.and i tried with this code
var val;
$(document).ready(function() {
$("a").click(function() {
window.val = $(this).attr("href");
alert(window.val);
});
it is working fine for the multiple links and which is inside the file that is local, here few demo links
a
b.....
but problem is i want that href value globally available because i'm using that in other file . My problem is how to make it global, or is there any other way to do it.
and how to write our own function to work the same thing without using $(document).ready function.
this whole thing in one html page but i want only href value in other html page , so if we write our own js function we can use this in both html pages . And that function should return href. but here i dono how to return to $(document).ready function.
You can create an object-based variable:
var screen = {
link:''
};
And then assign / access on click:
$('a').on('click',function(){
screen.link = this.href;
alert(screen.link);
});
I advocate this over assigning variables to the window ... a little more control this way.
Notice I used this.href instead of $(this).attr('href'). As the most interesting man in the world says, I don't always use vanilla JS, but when I do it's about 600,000 times faster.
EDIT So you want to get rid of $(document).ready() huh? Now you're venturing into the shark-infested waters of pure vanilla JS.
var screen = {
link:'',
assignLink:function(href){
screen.link = href;
alert(href);
}
},
links = document.getElementsByTagName('a');
if(window.addEventListener){
for(i = links.length; i--;){
links[i].addEventListener('click',function(){
screen.assignLink(this.href);
});
}
} else {
for(i - links.length; i--;){
links[i].attachEvent('onclick',function(){
screen.assignLink(this.href);
});
}
}
This is just winging it, so don't scathe me if it isn't flawless, its more to make a point. See why jQuery is so handy? All that extra crap is done in the background for you, so that you just need to deal with the burden of $(document).ready() and not have to deal with the rest of this kind of stuff.
EDIT AGAIN So ... you want to access this value across pages?
var screen = {
link:((localStorage['link'] !== null) ? localSorage['link'] : ''),
setLink:function(href){
screen.link = href;
localStorage['link'] = href;
alert(href);
},
getLink:function(){
return screen.link;
}
};
$('a').on('click',function(){
screen.setLink(this.href);
});
This use of localStorage is just an example ... you can get more elaborate or use cookies if you want IE7- to work, but this just providing ideas. You can set the value whenever you want using the screen.setLink function passing the href, or you can get the value whenever you want using the screen.getLink function.
Take a look at this example:
<!DOCTYPE html>
<html>
<head>
<title>Try jQuery 1.9.1 Online</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
var val;
$(document).ready(function() {
$("a").on('click', function() {
window.val = $(this).attr("href");
alert(window.val);
return false;
});
$("div").on('click', function() {
alert (val);
});
});
</script>
</head>
<body>
a
b
<div>click here</div>
</body>
</html>
Once you click either the link a or b val will be set. Clicking the div tag will alert you the current reference of val.
Declare val outside to make it global and you can use the val inside the function to set the href globally
var val;
$(document).ready(function() {
$("a").click(function(e) {
e.preventDefault();
val = $(this).attr("href");
alert(val);
});
});
jsfiddle

How can I covert this inline javascript to jQuery function which is causing conflict?

I am using a jQuery language switcher and below is the working script.
<script type="text/javascript">
window.lang = new jquery_lang_js();
$(document).ready(function() {
window.lang.run();
});
</script>
Switch to Japanese
However, the inline JavaScript is causing conflict with other jQuery scripts in the page.
I've tried to create a function like this below but obviously, this is not correct. By moving the .click function inside the document ready as suggested, it's working now.
<script type="text/javascript">
window.lang = new jquery_lang_js();
$(document).ready(function() {
window.lang.run();
});
$(".jp").click(function (e) {
e.preventDefault();
var $this = $(this);
var id = $this.attr('href');
window.lang.change('jp');
});
</script>
Switch to Japanese
Besides, I have other classes other than "jp" so this is not even the correct approach but I was trying to get rid of the inline javascript first; which I failed to do anyhow.
Can anyone please help?
/////////////////////Below works now ///////////////////
I guess now my question is, how can I rewrite it so that I do not repeat the code like this?
<script type="text/javascript">
window.lang = new jquery_lang_js();
$().ready(function () {
window.lang.run();
$(".jp").click(function (e) {
e.preventDefault();
var $this = $(this);
var id = $this.attr('href');
window.lang.change('jp');
$(".en").click(function (e) {
e.preventDefault();
var $this = $(this);
var id = $this.attr('href');
window.lang.change('en');
});
});
</script>
Switch to Japanese
Switch to English
.
.
. more classes
There is a better way than writing it like this, correct?
You should move the .click() inside of the .ready(). Right now, that JavaScript is running before the anchor loads, so the $('.jp') isn't finding it.
Also, don't use $this as a variable; this isn't PHP, and you're not using it for anything important anyway.

javascript onclick not working with `p.click =`

i have this simple code i just can't get it working.
<html>
<head>
<script type="text/javascript">
window.onload = function () {
p = document.getElementById("foo");
p.click = function() { alert(p); };
}
</script>
</head>
<body>
<div id="foo" style="position:relative;width:100px;height:100px;background-color:red;"> </div>
</body>
</html>
Javascript is turned on. If i put () after the function i can get it autorun. But still, the onclick is not working after it. Firebug did not show any errors.
I think you need to add an event-handler/listener for the 'click' event, rather than just specifying 'p.click = ...'
You could try this:
function whenLoaded() {
var p = document.getElementById("foo");
p.addEventListener("click", function(){alert(p)}, false);
}
document.addEventListener("DOMContentLoaded", whenLoaded, false);
*Note: attaching event listeners varies by browser, so youll want to use a library that abstracts the differences... Jquery can do this, and Bean ( https://github.com/fat/bean) is built for this. You could also check out Dustin Diaz's domReady if you're just looking for a small cross-browser DOM-loaded event handler kind of thang -- https://github.com/ded/domready
Please update as follow. Try.
p.onclick = function() { alert(p); };
p.onclick = function() { alert(p); };
and... remember to use var when you create a new var
var p = document.getElementById("foo");
If you're using jQuery, try this:
$(document).ready(function() {
p = document.getElementById("foo");
$(p).click(function(){
alert(p);
});
});

Why doesn't this click handler work in JQuery?

I've got the following code in my page:
var offer_link = $('<a>').addClass('fc-offer-link');
offer_link.click(function() {
alert('Hello');
});
offer_link.attr('href', "#" + this.id);
offer_link.append(this.subject);
this.list_item = $('<li>');
this.list_item.append(offer_link);
But even though the link appears on the page, the handler never gets called. What's going on?
The problem turned out to be where the item got inserted into the DOM. It was being inserted using:
$('#my_list').html(my_new_list.html())
It should have been using:
$('#my_list').replaceWith(my_new_list)
I think you just need to append the link to an element, like this:
<script type="text/javascript">
$(function(){
var link = $("<a>Click Me!</a>").addClass("fc-offer-link").appendTo($("#div1"));
if (link){
link.click(function(){
alert("Hey there!");
});
}
});
</script>
<div id="div1"></div>
EDIT: Not sure why I was downvoted, but here's a jsFiddle

Categories