Jquery: how to know which element was clicked? - javascript

I have an html code with 5 divs. They all have the same class, and different IDs.
Then, within javascript I have this:
$(".pics").click(function() {
alert("hey!");
});
where .pics is the name of the class of all the divs. The idea is that when I click on any of them, a certain script should be triggered, but I also want to know which one of the divs was clicked upon.
How do you go about it?
Thanks.

Assuming your ids are like this:
<div class="pics" id ="pic1">...</div>
<div class="pics" id ="pic2">...</div>
<div class="pics" id ="pic3">...</div>
<div class="pics" id ="pic4">...</div>
<div class="pics" id ="pic5">...</div>
Then in your javascript:
$(".pics").click(function() {
alert("You are clicking "+$(this).attr('id'));
});
And you should see something like this:
You are clicking pic1

Try this:
$(".pics").click(function() {
alert("hey!" + $(this).attr("id"));
});

You can get this information from the target of the click event, as shown here.
$(".pics").click( function (e) {
var clickedElement = e.target;
})

this refers to that element.
$(".pics").click(function() {
var me = $(this);
alert(this.id);
});

Related

how to Javascript toggle ID of div generated on runtime

I am sending a Model to a View in MVC,
and for each "Person" in my Model, I want to create a button that says "Show Details", when the user clicks it, a div with more information about that person toggles.
I am generating a a href and div id assigned to each person ID like the following:
foreach (var person in Model.Persons)
{
<div>
Show Details
</div>
<div id="#Html.Raw("detailsDiv-" + #person.id)">
<!--Content Here -->
</div>
}
I want to create the javascript that toggles on a click event
So I want to write this script but with the unique id for each person:
I want to get the id of the div that needs to be toggled.
I tried writing the script inside the foreach loop so I can be able to read the #person.id value, but it didnt work:
<script>
$(document).ready(function () {
$("#showDetails-#person.id").click(function () {
$("#details-#person.id").toggle();
});
});
</script>
Can anyone help?
put a class to your links like class="showDetails".
Now you Can create a global Event for all that links:
$('.showDetails').click(function(e) {
var id = this.id // extract id.. split with '-' or whatever..
$('#details-' + id).toggle();
});
you could put the id in a tag like "person_id" and use a class to trigger the jquery event.
<div class="middle_right">
<a class="showDetails" href="#" person_id="#Html.Raw("showDetails-" + #person.id)">Show Details</a>
</div>
and in js
$(".showDetails").click(function () {
var person_id=$(this).attr("person_id")
});

Efficient jQuery/JS - avoiding copy-paste the same code again & again

I need to write an efficient code in order to keep it simple & code file small, also I want to use the knowledge I hopefully get from here in future codes.
UPDATE: Just to be clear - my example is fixed "buttons" on browser window side & if you click on one of them, it takes you to div with same ID (look at code below).
IMAGE:
MY CODE EXAMPLE:
//Smooth Scroll Menu Links
jQuery('.div1').on('click', function(e) {
e.preventDefault();
jQuery('html,body').animate({scrollTop:jQuery(this.hash).offset().top-100}, 800);
});
//I have to copy-paste it 1000 times & only change the ".div1" to something else
//Note that I need a solution with different class names, not "div1", "div2" etc but e.g "location", "potato", "car" etc.
How to make this code working without writing same lines for every single div?
There got to be a way to get class from item you click & then scroll to item with same name ID, right? Or any other way to keep codes shorter in that kind of situations - otherwise it's just copy-paste-huge-file fest.
You can give each button a class so you can catch them all, than go to the element you want to scroll to by looking at the attribute of the clicked button :)
HTML
<div class="buttons" data-scroll="div1">div1</div>
<div class="buttons" data-scroll="div2">div2</div>
<div class="buttons" data-scroll="div3">div3</div>
<div class="content" id="div1">some content</div>
<div class="content" id="div2">some content</div>
<div class="content" id="div3">some content</div>
JS
$('.buttons').on('click', function(e) {
e.preventDefault();
var scrollTarget = $(this).data("scroll");
scrollme(scrollTarget);
function scrollme(target) {
$('html,body').animate({scrollTop:$("#"+target).offset().top}, 800);
}
});
example: http://jsfiddle.net/7gd66kr1/1/
try this i hope will work with you :
jQuery('div').on('click', function(e) {
e.preventDefault();
jQuery('html,body').animate({scrollTop:jQuery(this.hash).offset().top-100}, 800);
});
note that : this function will aplay on all divs in page
I think there are more than an unique solution. If you don't want to modify your HTML, then you need a condition to determine if the clicked element is an "active" one:
jQuery('div').on('click', function(e) {
var id = $(this).attr('class');
var scrollto = $('#' + id);
if(scrollto.length > 0) {
e.preventDefault();
jQuery('html,body').animate({scrollTop:scrollto.offset().top-100}, 800);
}
});
If you "can" modify your HTML, it's wise to add some attribute to the "active" elements (the ones that are buttons), so you know they scroll the page, or put them inside a container. The attribute you add may be a class or any other valid attribute (I recommend "rel", but might be "data" as spotted by #Iliya Reyzis , who selects by class and scrolls to "data") and select them by it:
<div class="div1" rel="mybutton">div1</div>
jQuery("[rel='mybutton']").on('click', function(e) {
var id = $(this).attr('class');
var scrollto = $('#' + id);
e.preventDefault();
jQuery('html,body').animate({scrollTop:scrollto.offset().top-100}, 800);
});
Hope it helps!!

remove onclick when attached to children

I have the following code:
layoutOverlaysBldg = $("#layout-overlays-bldg")
layoutOverlaysBldg.on("click", "div", function(event) {
var floor;
console.log("floornum: " + this.dataset.floornum);
floor = parseInt(this.dataset.floornum);
...
$("#choose-floor").fadeOut();
$("#choose-apt").fadeIn();
});
later - based on data I'm getting back from the DB - I want to remove some of the .on("click", "div", ...) from only some of the divs. I already have the selector that is getting the right divs but I cannot figure out how to remove the click event. I have tried .off("click") after selecting the right div but it has no effect.
This issue here is because you are using a delegated event. You can add or remove the event for all child elements, but not individual ones given your div selector.
With that in mind the easiest way to do what you need is to add the event based on a class, then add and remove that class on the children as needed. Something like this:
layoutOverlaysBldg = $("#layout-overlays-bldg")
layoutOverlaysBldg.on("click", "div.clickable", function(event) {
// your code...
});
You can then enable/disable the event on the child div by adding or removing the .clickable class.
You can try like this :
Example :
<div id="test">
<div id="first">first</div>
<div id="second">second</div>
</div>
<div onclick="unbindSecondDiv();">UNBIND</div>
<script>
function unbindSecondDiv()
{
test = $("#second")
test.unbind("click");
alert('Selected Area Click is Unbind');
}
$(document).ready(function(){
//BIND SELECTED DIV CLICK EVENT
test = $("#test > div")
test.bind("click" , function(event) {
alert($(this).attr('id'));
});
});
</script>
In the above example , selected DIV elements click event is bind.
And after execute function unbindSecondDiv() , second DIV click event will be unbind.
Have a try , may helps you.

Show/hide div on click if div class names match

I have two sets of divs — one that is the 'main' div and one that is the 'extra' div. Both of these have classes that are brought in via the CMS.
What's the best way of showing/hiding (preferably slideToggle) each div, on click, that corresponds to the div clicked?
<div class="each-business-content-main" data-id="group-1"></div>
<div class="each-business-content-main" data-id="group-2"></div>
<div class="each-business-content-extra group-1"></div>
<div class="each-business-content-extra group-2"></div>
These 'group-1' or 'group-2' classes aren't known in advance so can't be hard-coded in. Essentially I'm wondering how, if you click on one div it shows another div (as long as they share the same class name).
I've tried this so far:
$('.each-business-content-main').on('click', function (e) {
e.preventDefault();
var id = $(this).data('id');
jQuery('.each-business-content-extra').slideUp();
jQuery('.each-business-content-extra .' + id).slideDown();
});
But I'm guessing hrefs and id might come in useful? Or some other data-id...
If you assign a data attribute to your divs it makes this pretty easy:
<div class="each-business-content-main group-1" data-group="1">main 1</div>
<div class="each-business-content-main group-2" data-group="2">main 2</div>
<div class="each-business-content-extra group-1" data-group="1">extra 1</div>
<div class="each-business-content-extra group-2" data-group="2">extra 2</div>
$('.each-business-content-main').click(function () {
$('.each-business-content-extra.group-' + $(this).data('group')).slideToggle();
});
jsFiddle example
Have you tried replacing this:
jQuery('.each-business-content .' + id).slideDown();
...with this:
jQuery('.each-business-content #' + id).slideDown();
jQuery selects classnames as .classname and IDs as #id.
Try
$('.each-business-content').click(function () {
var that = $(this);
$('.each-business-content').each(function () {
if ($(this) === that) {
$(this).slideUp();
} else {
$(this).slideDown();
}
});
});
Can you try this code at jsFiddle? Don't need group 1 and group 2, I use index instead of the name of the id. Is that all right for you?
$('.each-business-content-main').on('click', function (e) {
$('.each-business-content-extra').(':eq(' + $(this).index() + ')').slideDown();
$('.each-business-content-extra').not(':eq(' + $(this).index() + ')').slideUp();
});

How do I get the ID of a particular class using jQuery?

I have some div elements having class name hover, these div elements have parent divs having class name hoverparent but the id's of these parent elements are different.
Is it possible to get the ID of respective .hoverparent element while hovering on my .hover div elements?
I tried to get this by:
$('.hoverparent').attr('id')
But it gives the same first parent id every time.
Structure is like:
<div class="hoverparent" id="hover-1">
<div class="hover">ABC</div>
</div>
<div class="hoverparent" id="hover-2">
<div class="hover">DEF</div>
</div>
You need to use the parent or closest functions to traverse up the DOM tree to find the "parent" element you are looking for:
$(".hover").hover(function() {
var $parent = $(this).closest(".hoverparent");
alert($parent.attr("id"));
});
The difference between parent and closest is that the first will only work if the .hoverparent element is the immediate parent of the .hover element; closest will search upwards through all ancestors to find it.
try $(this).parent().attr('id') , in your hover callback.
$('.hover').mouseover(function() {
$(this).parent().attr('id');
});
don't call your class hover. this should work
$(".hover").hover(
function () {
var id = $(this).parent().attr('id');
});
Add each loop like this :
$(".hoverparent").each(function(){
var id=$(this).attr("id");
alert(id);
});
Use the parent method in the handler for the hover event:
$('.hover').hover(function(evt){
var par = $(this).parent().attr('id');
//Now do with ID what you need
},
function(evt){
//presumably you don't need anything for mouseout
});
You can try the parent() method.
Like this:
$('a').click(function(){
var parentId = $(this).parent('div.hoverparent').attr('id');
});
Try the following:
$('.hover').hover(function() {
var parentID = $(this).parent().attr('id'); alert(parentID);
});
$(".hover").hover(function(){
console.log($(this).closest(".hoverparent").attr("id"));
});
here is the fiddle http://jsfiddle.net/9dJJ9/1/show/

Categories

Resources