I have some hyperlinks and when user clicks on any of them I want to direct the user to that particular link. I am accessing the href attribute with jquery. Below is the code.
link1
link1
link1
Now I want to access the URL with jQuery I am using the below code:
$(document).ready(function() {
$('.class-name').click(function(){
var linkHref=$("this.class-name").attr('href');
alert(linkHref);
$('.redirect').attr('href',linkHref);
});
But I am getting "undefined" in the alert.
All your help is highly appreciated.
Change your code like this
$(document).ready(function() {
$('.class-name').click(function(){
var linkHref=$(this).attr('href');
alert(linkHref);
});
this is the object < a > that you selected with the click method. Thus you do not need to let jQuery search for the object based on class or id as previously. Hope this clarifies.
var linkHref=$(this).attr('href');
Your selector is wrong.
this is a special identifier that gets the context that your function is called in. It doesn't make sense to write "this"; the jQuery function has no way of knowing what your this is.
You probably want $(this).
You can also write $(this).find('.redirectLink'), but that isn't the code you're looking for.
In jQuery this refers to the current object in scope. In the case of a click event this refers to the hyperlink being clicked. But do not enclose it in quotes.
$(document).ready(function() {
$('.class-name').click(function(){
var linkHref=$(this).attr('href');
alert(linkHref);
$('.redirect').attr('href',linkHref);
});
});
you could shorten this to:
$(document).ready(function() {
$('.class-name').click(function(){
$('.redirect').attr('href',$(this).attr('href'));
});
});
Related
I've been looking for so long and found several answers that suggest using .on() as in $('.idOfMyElemenet').on() works even for elements that don't exist yet. But this doesn't seem to be finding the element. Am I doing something wrong?
The highest level <span> (in screenshot) does not exist until I click on a drop-down. Ultimately I'm trying to trigger an event when the user clicks on any of the <li> (aka selects an option from the drop-down).
$(document).ready(function () {
var test = "#select2-id_customer-results";
$(test).on("click", function() {
console.log('hello')
})
})
EDIT:
Thanks to Drew Baker - I think his second solution is the way to go. But not quite there yet...
From the select2 documentation
All public events are relayed using the jQuery event system, and they
are triggered on the <select> element that Select2 is attached to.
So I tried listening to it via the id (which doesn't seem to exist but would probably be id_customer) and the class. The class I added below did not work. Is there a way to listen to this using Jquery?
$(document).ready(function () {
// console.log($('#id_customer'));
$('.modelselect2 form-control select2-hidden-accessible').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
});
});
I'll answer your question, but then give you a better solution.
First, you need to make sure the thing you are attaching .on() to actually exists. I typically use a containing DIV or failing that body or html will work.
Secondly you are missing a parameter that tells jQuery the thing you are looking to watch to be clicked on. In this case, I'm assuming it is the UL tag with the ID you provided.
This should do what you want:
$(document).ready(function () {
$('body').on("click", "#select2-id_customer-results", function() {
console.log('hello')
})
})
But a better solution would be to use the Select2 API to have it tell you when something is selected. This will be way more reliable and should make your code work after upgrades to Select2.
Something like this:
$('select[name="customer"]').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
});
NOTE: #mySelect2 is probably not what you have. Use whatever ID you used to initialize Select2 in jQuery.
You can read more about that API here: https://select2.org/programmatic-control/events
if your element is dynamically generated and you want to target that specific element. You need to specify a static container/parent element to indicate where it belongs.
Try this:
$( '#dynamicallyAddedElement' ).on( 'click', '#wrapper', function () { ... });
//where #wrapper is a static parent element in which you add the dynamic links.
So, you have a wrapper which is hard-coded into the HTML source code:
PS. Hope I helped in some way.
If you need to trigger an event when click on <li> elements, you have to use that elements id or class as the selector. Check the below code:
$(document).ready(function () {
var test = ".select2-results__option";
$(test).on("click", function() {
console.log('hello')
})
})
It turns out this is an old bug in django-auto-complete.
The code below works. I have no idea why but now I can move on.
Note: the 'name' is the value of the select2 select element (see screenshot at bottom)
document.querySelector('select[name="customer"]').onchange=function() {
console.log("myselect2name changed");
};
I need something like .load() but that can only work for images and iframes. I would want to do this in order to automatically attach a selector element in "this" variable.
$('document').ready(function({
$('a').<Something to automatically run the stuff below when page is loaded>(function(){
// Placeholder is to store the href somewhere so the link does not go to a webpage atm.
$(this).attr('placeholder',$(this).attr('href'));
$(this).attr('href','javascript:');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My Link
I am not sure if you want to achieve this simple thing ? :
$('document').ready(function({
$('a').each(function(){
$(this).attr('placeholder',$(this).attr('href'));
$(this).attr('href','javascript:');
});
});
$('element').each allows to loop over all elements, and you can use $(this) inside closure to modify the element itself.
jQuery supports chaining so the simplest and most likely the most performant answer is:
$('document').ready(function({
$('a').each(function() {
var a$ = $(this);
a$.attr('placeholder',$a.attr('href'))
.attr('href','javascript:void(0)');
});
});
Everytime you call $(this) it has to create a new jQuery wrapper around this which you might as well cache via a variable.
I am trying to use jquery mouse enter and mouse leave functions .
this is my code :
html :
<ul class="menuList bold">
<li id="tevee">
<span>test</span>
</li>
</ul>
jquery
$(function(){
$(".tevee").on("mouseenter",".menuList",hoverInFunction());
$(".tevee").mouseleave(hoverOutFunction("tevee"));
});
function hoverInFunction()
{
alert("hi")
}
function hoverOutFunction(variable)
{
alert("test");
}
https://jsfiddle.net/tejareddy/dndvsudh/ . this is my fiddle , they are not working instead they are triggering on page load and not every time when i hover on them .
Remove the ()
change
$(function(){
$("#tevee").on("mouseenter",".menuList",hoverInFunction());
});
to:
$(function(){
$("#tevee").on("mouseenter",".menuList",hoverInFunction)
});
or do it like this:
$("#tevee").on("mouseenter",".menuList",function(){
alert("hi")
}).on("mouseleave",".menuList", function(){
alert("test");
});
Firstly, your selector was incorrect for the ".on" call, secondly, you were using parenthesis when referring to a function (which in this case must be referred to as an object without the parenthesis).
$(function(){
$(".menuList").on("mouseenter","li",hoverInFunction);
$(".menuList").on("mouseleave","li",hoverOutFunction);
})
Please see the fixed version here
You may use event.data if you wish to pass parameters into the calls.
The original method of binding the event to the ID is not what .on is all about, it's best to bind to a higher-level object in the DOM (such as the actual menuList) and then write a selector which will affect the children on it. That way you get "delegated eventing" and any dynamically added items will still work the way you want them to.
Once again I've inherited someone else's system which is a bit of a mess. I'm currently working with an old ASP.NET (VB) webforms app that spits JavaScript onto the client via the server - not nice! I'm also limited on what I can edit in regards to the application.
I have a scenario where I have a function that does a simple exercise but would also need to know what item was clicked to executed the function, as the function can be executed from a number of places within the system...
Say I had a function like so...
function updateMyDiv() {
$('#div1').hide();
$('#div2').hide();
$('#div13').show();
}
how could I get the ID (for example) of the HTML element that was clicked to execute this?
Something like:
function updateMyDiv() {
alert(htmlelement.id) // need to raise the ID of what was clicked,
$('#div1').hide();
$('#div2').hide();
$('#div13').show();
}
I can expand on this if neccessary, do I need to pass this as an arguement?
The this keyword references the element that fired the event. Either:
<element onClick="doSomething(this);">
or
element.onclick = function() {
alert(this.id);
}
Bind your click events with jQuery and then reference $(this)
$('.myDivClass').live('click', function () {
updateMyDiv(this);
});
var updateMyDiv = function (that) {
alert(that.id);
// save the world
};
You don't need to pass "this", it is assigned automatically. You can do something like this:
$('div').click(function(){
alert($(this).attr('id'));
})
Attach the function as the elements event handler is one way,
$(htmlelement).click(updateMyDiv);
If you are working with an already generated event, you can call getElementByPoint and pass in the events x,y coords to get the element the mouse was hovering over.
$('.something').click(function(){
alert($(this).attr('id'));
});
You would need to pass it the event.target variable.
$("element").click(function(event) {
updateMyDiv($(event.target));
});
function updateMyDiv(target) {
alert(target.prop("id"));
}
Where is your .click event handler? Wherever it is, the variable this inside of it will be the element clicked upon.
If you have an onclick attribute firing your function, change it to
<tag attribute="value" onclick="updateMyDiv(this)">
and change the JavaScript to
function updateMyDiv(obj) {
alert(obj.getAttribute('id')) // need to raise the ID of what was clicked,
$('#div1').hide();
$('#div2').hide();
$('#div13').show();
}
use the .attr('id') method and specify the id which will return what you need.
I'm using jQuery to get a click on an 'a' element. I have a list of those links where each one has a class which by him I'm capturing the click.
I would like to know which of the links has been clicked (I have an attribute 'setid' for each link) and also get the point where the mouse has been clicked.
How could this be accomplished?
example of the code:
click me
$('.newItem').click(function (e) {
alert(e.attr('setid'));
});
EDIT:
OK, so to get the position I would use e.pageX
To use jQuery methods you have to wrap this with a call to jQuery.
$('.newItem').click(function () {
alert($(this).attr('setid'));
});
refer to the code given below:
document.getElementById("element_id").addEventListener("click",function(e)
{
console.log(e.srcElement.getAttribute("data-name"));
},false);
Like Skylar said in the comment to your question, you can use "data-" in front of your new attribute (which is HTML5 valid).
click me
Then in jQuery (v1.4.3+) you can get it like:
var setid = $(this).data("foo");
It's even a little nicer than attr() that other people have mentioned. See this for more examples - http://www.broken-links.com/2010/11/18/data-attributes-in-html-and-jquery/
You're on the correct path.
$(function(){
$('.newItem').click(function () {
alert( $(this).attr('setid') );
})
});
Your code is almost right to get the attribute. The only thing missing is wrapping this (a DOM element) in the jQuery wrapper so you can use jQuery functions. $(this).attr('setid') should work.
To get the page coordinates, use the pageX and pageY properties of the event object. So:
$('.newItem').click(function (e) { // e is the event object
alert($(this).attr('setid'));
alert(e.pageX);
alert(e.pageY);
});
See the documentation on the Event object.