I have the following HTML:
<div class="eventContainer" id="dennaVecka" style="background-color: #2B4699;">
<p>Denna vecka</p>
</div><!--eventContainer ends-->
<div class="eventList" id="dennaVecka_table">
...
</div>
And the following jQuery:
eventID = null;
$('.eventContainer p, .eventContainer').click(function (e) {
//eventID = $(this).attr('id');
eventID = e.target.id;
$('.eventList#' + eventID + '_table').fadeIn(300);
//alert(e.target.id);
});
I want: When div class eventContainer or the paragraph inside it is clicked, I want to use the ID of eventContainer (id="dennaVecka") to display the div class eventList beneath it. My problem with the current setup is that I don't know how to get the ID of eventContainer if the paragraph is clicked. If I click the paragraph I will get the ID of the paragraph ("undefined").
Is there a way to get the ID of eventContainer in jQuery no matter if I click the div or the paragraph?
Maybe I should setup the HTML in another way?
Use the fact that click event bubbles up to the parent container. In this case you can bind only one event handler to .eventContainer and read this.id to get container id:
$('.eventContainer').click(function (e) {
eventID = this.id;
$('.eventList#' + eventID + '_table').fadeIn(300);
});
So if you click p element inside .eventContainer event will still be handled by above listener on .eventContainer, with this pointing to it.
Related
So I have a list of items with anchor a that successfully listen to the following event:
$('body[data-link="media"] #media_content a').on('click',function(e){
e.preventDefault();
var page = $('.page.active a')[0].innerHTML;
var date = $('.year_sorting .filter_years').val();
var id = $(e.currentTarget).data('media');
window.location.href = 'http://'+basePath+'media/content/'+id+'?date='+date+'&page='+page;
})
However in the same page, there is a filter allowing the user to change the year filter and once changed, the following execute and append a list of items that has the exact same layout as the a above $('body[data-link="media"] #media_content a'), which supposes to listen to the above event as well. the filter event is below:
$('.activity.filter_years').on('change',function(){
$('.pagination_ul').remove();
r_year = $(this).val();
$.get("media/getActivity",{type:'0',key:r_year}).done(function(d){
if(d.length>0){
$('#media_content').html('');
var ul = '<ul class="ap pagination-sm pagination_ul"></ul>';
$('.pagination_menu').append(ul);
for(var i=0;i<d.length;i++){
var p = ['',''];
if(!d[i].event_period){
p = ['style="color:#8A8A8A;"','style="color:#C7C7C7;"'];
}
if(locale=='en'){
var event = $('<div class="div_media_content_f2 '+d[i].pagination+' pagination-tr"> <div class="div_media_content_f2_3"> <span class="font12_bold">'+d[i].event_date+'</span> <div>'+d[i].event_title+'</div></div></div>')
}else if(locale=='hk'){
var event = $('<div class="div_media_content_f2 '+d[i].pagination+' pagination-tr"> <div class="div_media_content_f2_3"> <span class="font12_bold">'+d[i].event_date+'</span> <div>'+d[i].event_title_zh+'</div></div></div>')
}else {
var event = $('<div class="div_media_content_f2 '+d[i].pagination+' pagination-tr"> <div class="div_media_content_f2_3"> <span class="font12_bold">'+d[i].event_date+'</span> <div>'+d[i].event_title_cn+'</div></div></div>')
}
$('#media_content').append(event);
}
pagination('.pagination_ul','.pagination-tr',Math.ceil(d.length/20),false);
}else{
$('#div_news_content_right').html('').append('<div class="not_available">No content available</div>');
}
})
})
in which you can see the list of items are being appended into the layout by JS. However, even with the same layout $('body[data-link="media"] #media_content a'), such appended list of items do not listen to the onclick event. the above js codes are together in a separate js file apart from the html file where I tried to put the first a event into the html file but the new appended list of items still do not listen.
Cannot think of other work around at the moment, please help to see what would be the cause of it. Thank you.
Maybe simple try this.
$(document).on('click', 'body[data-link="media"] #media_content a')
If your element is dynamic create you should bind the click event on document and target what's element should dispatch the event.This is different to bind click only on element because the event will unbind while you remove the element.
Updated:
I'm not sure I've understand all the script you have but I try to simplify the issue.
This is the jsbin and its work correctly.
JSBin
I created new website and on it I want when I click on one div jquery show me div ID and I user this command and I can give div ID
var name = $(this).attr("id");
and when I want to give div's child I use this Command
var name = $(this).children(".select").attr("name");
now I have 3 divs like this
enter image description here
and when I click on div 3 Jquery give me div2 with this command
var name = $(this).children(".select").attr("name");
how can I get div's ID when click on it?
example click on div 1 show me div 1 or when I click on div 2 show me div 2
and when I click on div 3 show me div 3
Thanks
Your first code was correct, you don't need to find children...
$("div").click( function(){
var name = $(this).attr("id");
console.log( name );
});
If you have trouble with multiple events, you can stop propagating the click event with .stopPropagation() like so:
$("div").click( function( e ){
var name = $(this).attr("id");
console.log( name );
e.stopPropagation();
});
See example: https://jsfiddle.net/tg4rmkk9/
You've already solved the main part of the problem:
var name = $(this).attr("id");
This will get you the ID of the Div.
To alert it you can then do alert(name);
Here's a demo of what I think you're going for :
$('[id^=div]').on('click', function() {
alert($(this).attr('id'));
});
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<div id="div1">
Click me
</div>
<div id="div2">
Click me too
</div>
<div id="div3">
Click me three
</div>
(see also this Fiddle)
I'm trying to set up a click event for a bunch of dynamically generated divs. However, sometimes when I click on the div, the click function is invoked with an event.target that is not the div the click function was assigned to. This is happening when I click on the div close to its text rather than in empty space within the div. How can I stop this?
Here's the code I'm using to set up the divs:
for (i = 1; i <= pageArray.length; i++) {
var divName = "div_" + i
console.log("adding divname with id " + divName);
console.log("<div id = '" + divName + "' class = 'unselected' style = 'overflow:hidden; background-color: yellow; float:left;'></div>");
$('#toAppend').append("<div id = '" + divName + "' class = 'unselected' style = 'overflow:hidden; background-color: yellow; float:left;'></div>");
$("#" + divName);
.load(pageArray[i - 1]);
.css("width", Math.round(widthPer * portionDiv));
.css("height", heightPer).css("background-color", COLORS[i]);
.css('cursor', 'pointer');
// expand section user clicks on and collapse other sections
.click(function(event) {
console.log(event);
console.log("here's id " + event.target.id);
var div = "#div_" + event.target.id.slice(-1);
console.log("here's div " + div);
});
}
That code is in the $(document).ready function. It seemed to be working fine, then it got real slow, and I started trouble-shooting and realized the click was not always related to its associated div. The code is running here with some log statements. Here's an example of console output:
accordion.js:24 adding div element with id div_1 <--- so we can see the divs set up properly
accordion.js:24 adding div element with id div_2
accordion.js:24 adding div element with id div_3
accordion.js:24 adding div element with id div_4
accordion.js:35 here's id div_2
2accordion.js:35 here's id <--- what?!?! seems to think it's being called from contents of div rather than from div
accordion.js:35 here's id div_4
accordion.js:35 here's id
accordion.js:35 here's id div_2
accordion.js:35 here's id
accordion.js:35 here's id div_2
What am I missing? Why is the click event not binding to its associated div exclusively and how can I fix this?
If you use event.target you'll get the actual element that was clicked on, even if it is a child of the element the click handler was attached to. To identify it's parent you should use event.currentTarget.
Identifies the current target for the event, as the event traverses the DOM. It always refers to the element the event handler has been attached to as opposed to event.target which identifies the element on which the event occurred.
Mozilla doc
In your case target can be h2 and currentTarget will always be the div itself.
I have following code
<div id = "fa10_holder">
<div id = "b-1"></div>
</div>
I am adding this dynamically in a div that holds all of these type of divs ..
lets say if I add another div it would be like this
<div id = "fa11_holder">
<div id = "b-2"></div>
</div>
Now the problem is when I click the div with id of b-1 or b-2 and so on I want the id of its parent like fa10_holder and the id of the clicked div aswell... can any one help me ??
Like this working demo another way.
APIs:
parents - http://api.jquery.com/parents/
attr or prop - http://api.jquery.com/attr/ or http://api.jquery.com/prop/
I have added extra class, in case you have many div you can have a blanket click via class. :)
Extra: When to access the attribute (vs the property)?
code
$(document).ready(function () {
$(".hulk").click(function () {
alert($(this).parents('div').attr('id'));
alert($(this).attr('id'));
});
});
html
<div id = "fa11_holder"> parent
<div id = "b-2" class="hulk">hulk</div>
</div>
var thisid = this.id;
var parrentid = $(this).parent().attr('id');
I want to select the id of the current div when I click on it in jQuery.
For example, say I have HTML like this:
<div class="item" id="10">hello world</div>
<div class="item_10">hello people</div>
When I click on the first div on .item class, I want to copy the id of the current div + adding to it the number (10), so it will be ("div id" + 10) equal to the second dev class = item_10.
I tried to use currentid = this.id; but it doesnt work :( !
First, note that id attributes starting with numbers are syntactically illegal in HTML4. If you're using id="10" make sure that you're using the HTML5 doctype (<!DOCTYPE html>).
It's hard to say why what you were doing didn't work without seeing your actual code. Presumably it is because you were registering for the event on a higher element (like the body) and this.id was the id of that higher element and not the element you clicked on.
In this case, you want to use the target property of the event to find what you clicked on. For example:
$(document.body).click(function(evt){
var clicked = evt.target;
var currentID = clicked.id || "No ID!";
$(clicked).html(currentID);
})
Seen in action: http://jsfiddle.net/Gra2P/
If you were registering on the specific elements instead, then this.id does work:
$('div').click(function(evt){
var currentID = this.id || "No ID!";
$(this).html(currentID);
})
Seen in action: http://jsfiddle.net/Gra2P/1/
This is sub-ideal, however, because:
It makes many event handler registrations instead of 1, and
If additional divs are added to the document after this code is run, they will not be processed.
Under jQuery 1.7, you use the .on method to create a single event handler on a parent element with selectors for the kinds of elements you want to catch the event on, and have this set to them. In code:
$(document.body).on('click','div',function(evt){
var currentID = this.id || "No ID!";
$(this).html(currentID);
})
Seen in action: http://jsfiddle.net/Gra2P/2/
I think you're trying to do something like:
$(".item").click(function(){
var id = $(this).attr("id");
var el = $(".item_" + id);
});
Now el is your second div.
You can simply use this.id
$('div').click(function() {
var divid = this.id;
alert($('.item_'+divid).html());
});
Demo
Something like this?:
$('div').click(function() {
theId = $(this).attr('id');
//Do whatever you want with theId.
});
This can be done as:
$('.item').click(function() {
var divId = $(this).attr("id");
});