I'm trying to attach a mouseover event to all img elements of a gallery in a page (using Mootools). This is easy enough using something like
$$('img.mygalleryclass').addEvents({
mouseover: function(){
alert(id);
}
});
My question is, how do I alert the id of the element referenced in the $$ 'loop'? That "alert(id)" returns an error every time since id is not defined.
Thanks!
Pass the event argument to the mouseover function and then get the id of the target:
$$('img.mygalleryclass').addEvents({
mouseover: function(e) {
alert(e.target.id);
}
});
Here's an example.
Related
I want to make a web site for a photos.
Inside a dynamic div created with a jquery function (.append) there is this anchor:
<a href='#' style='color:green;' id='"+this.foto_id+"' data-id='"+this.foto_id+"' class='modificaDataFoto modificaDataFoto"+this.foto_id+"'>Modifica</a>
The page is load normally and if I use the browser debugger I see all the HTML code including all dynamic data from database...
But if I try to set a class of the anchor in a jquery function it doesn't run:
$('.modificaDataFoto').bind('click', function(event) {
event.preventDefault();
var idFotoModifica= $(this).attr("data-id");
console.log(idFotoModifica);
$("dataFoto"+idFotoModifica).focus();
$("dataFoto"+idFotoModifica).css("color", "red");
$(this).attr("class", "modificaDataFotoConferma");
});
Why does that function not work?
.bind() only works on elements that are already present in the DOM. It's likely that you're trying to bind the click event to the element before the dynamic element exists.
There are two ways to fix this:
wait until after the <a> element has been appended to the document before running your $('.modificaDataFoto').bind(), or
Delegate the click event from a non-dynamic element (or the document itself):
$(document).on('click', '.modificaDataFoto', function() {
// this is essentially the same as your existing function; I've
// consolidated it a bit and removed the no-longer-needed preventDefault.
$("dataFoto" + $(this).attr("data-id")).css("color", "red").focus();
$(this).attr("class", "modificaDataFotoConferma");
}
Use this code:
$(document).on('click', '.modificaDataFoto', function(event) {
event.preventDefault();
var idFotoModifica = $(this).attr("data-id");
console.log(idFotoModifica);
$("dataFoto"+idFotoModifica).focus();
$("dataFoto"+idFotoModifica).css("color", "red");
$(this).attr("class", "modificaDataFotoConferma");
});
I'm not entirely sure if I understood your question but if you are trying to change the element's class name then you can simply do this:
$( this ).switchClass( "old class", "modificaDataFotoConferma", 1000, "easeInOutQuad" );
instead of
$(this).attr("class", "modificaDataFotoConferma");
You also have the .toggleClass()
EDIT:
You can also use removeClass() and then use the addClass().
Where does this reference to in a delegated .on event?
Example:
$('#foo').on('click', $('.bar'), function() {
console.log(this);
});
In the example this will reference to #foo. But how do i access the bar element that got clicked? I might have 5 bar elements and I want to know which one was clicked.
Thanks
Edit:
Sorry i changed #bar to .bar (since it exists multiple times).
The answer that i should just use '.bar' helped. But what if i have selector like this:
$('.bar').find('a');
How would i incorporate something like this?
This won't work: (cause this will reference to #foo)
$('#foo').on('click', $('.bar').find('a'), function() {
console.log(this);
});
Change it to this...
$('#foo').on('click', '.bar', function() {
console.log(this);
});
Now this will be the clicked .bar.
If you want a jQuery object then use $(this) as normal.
Edit
As per the change to question code, you'll need this...
$('#foo').on('click', '.bar a'), function() {
console.log(this);
});
That simply extends the click event handler to links inside .bar elements that may not exist at document.ready.
Two ways.
Use a string selector, not a jQuery object, when calling .on():
$('#foo').on('click', '#bar', function() {
console.log(this); // #bar
});
Specify a parameter name for the jQuery normalised event object, and use its target property:
$('#foo').on('click', $('#bar'), function(e) {
console.log(this); // #foo
console.log(e.target); // #bar
});
EDIT: Ignore the second option. jQuery doesn't accept a jQuery object for the selector, and as a result simply ignores it. You will not be setting up event delegation, you'd instead just be setting a static click event handler on #foo, which works due to event propagation.
An ID should be used once in a page. So you can add a class fooClass to your 5 elements and do :
$('.fooClass').onclick(function() {
alert("my bar element: " + $(this));
});
and do what you want with $(this).
I want to know how to check if my image was clicked using jquery...
Here is my html code
<img class="img-fade" src="img/message.png" id="messages" />
And my jquery code im using:
$('#messages').on("click", "img", function (e) { alert('hi'); }
But it still isnt working,
Could anyone help? Thanks :D
When you do:
$(selector1).on(event, selector2, function);
jQuery binds a handler to the event on the DOM elements that match selector1. When this handler runs, it walks the DOM hierarchy from the most specific element up to the element matching selector1, and checks whether any of the elements matches selector2. If it finds a match, it calls function with the appropriate execution context.
This is how on() is able to handle events on DOM elements that are added dynamically after the delegation is created.
i want to know how jquery' delegate or on(for delegate) works
In your case you made selector1 and selector2 the same element which caused trouble.
You can try this too
$('#messages').click(function(){
alert('hi');
}
$(function() {
$('#messages').on("click", function (e) {
$('.content2').fadeOut(3000);
window.setTimeout(function() {
window.location.href = 'messagecenter.html';
}, 3050);
});
});
I just fixed it :)
Instead of having $('#var').on("click", "img", function(e)) {});
I just removed the "img" part which I don't think was needed.
Thanks :)
So, I have 10 links like this:
and on function. Like this:
$(document).on("click", ".testclass", function () {
alert($(this).attr('data-test'));
});
I cannot understand how can I get data-test attribute for a specific a tag in this case. $(this) returns document object and not a
You have to bind the listener to the anchor, not the document:
$('a.testclass').on('click', function() {
alert($(this).data('test'));
})
And data function is the right way to get data attached to a DOM element.
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.