I'm trying to detect which div box was clicked with JQuery and I'm not sure what I am doing wrong. I'm aware that I can approach this in a different method by directly calling functions if a div box is clicked, but I wish to do it this way by first determining what was clicked.
$(document).ready(function() {
$(document).click(function(event){
var id = event.target.id; //looks for the id of what was clicked
if (id != "myDivBox"){
callAFunction();
} else {
callSomeOtherFunction();
}
});
});
Thank you for any suggestions!
You could use the closest function to get the first ancestor element with tag div, see following example:
$(document).ready(function() {
$(document).click(function(event){
var parentDiv = $(event.target).closest("div");
console.log(parentDiv.prop("id"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">
<span id="span1">Test1</span>
</div>
<div id="div2">
<span id="span2">Test2</span>
</div>
I hope it helps you. Bye.
No matter what you click, you will always know the element that was clicked:
$("#myDiv").click(function(e){
alert("I was pressed by " + e.target.id);
});
Knowing that you don't want to add this to every div, and you have your click on your document, you'll need to figure out what divs can be reported as "clicked".
In order to do this you'll either need a strict hierarchy of elements in your DOM (which is anoyingly bad) or you can decorate "clickable" div's with a specific class.
Fiddle - similar to below. https://jsfiddle.net/us6968Ld/
I would use closest in Jquery to get the result you want.
$(document).ready(function() {
$(document).click(function(event){
var id = event.target.id;
var clickDiv = $(event.target).closest('div[class="clickable"]');
alert(clickDiv[0].id);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="clickable" id="clickable1">
<span id="foo"> click me - Foo - clickable 1</span>
</div>
<div id="notClickable1">
<div class="clickable" id="clickable2">
<span id="span1">
Click Me Inside Span 1 - clickable 2
</span>
</div>
<div class="clickable" id="clickable3">
<div id="notClickable2">
<div id="notClickable3">
<span id="click me">Click Me - clickable 3</span>
</div>
</div>
</div>
</div>
try this:
$('div').click(function() {
alert($(this).attr('id'));
});
https://jsfiddle.net/1ct0kv55/1/
Related
I'm trying to do a tag filtering function in the website. The transferring from one div to another works. But transferring it back doesn't work.
This is my html:
<h4>Video Tags</h4>
<div id="tagbox-1">
<span class="tag-filter">tag 1</span>
<span class="tag-filter">tag 2</span>
<span class="tag-filter">tag 3</span>
</div>
<h4>Video Filters</h4>
<div id="tagfilter-1">
</div>
Then this is my javascript/jquery:
function tag_ui_move(tag_object,filter_move_to){
$(filter_move_to).append($(tag_object)).fadeIn();
$(tag_object).remove();
}
$(document).ready(function(){
var stored_tag = [];
$('[id^="tagbox-"] > span').each(function(){
$(this).click(function(){
tag_ui_move(this,'div[id^="tagfilter-"]');
});
});
$('div[id^="tagfilter-"] > span').each(function(){
$(this).click(function(){
tag_ui_move(this,'div[id^="tagbox-"]');
});
});
});
This is pretty much the gist of my html and code. I simplified it because there are more tagbox- and tagfilter- divs.
The problem is that $('[id^="tagbox-"] > span') selects all of the tag span elements that exist in the tagbox at that moment and then you bind a click handler to each of them that moves it to the filter div. And then $('div[id^="tagfilter-"] > span') selects all of the tag span elements that exist in the filter div at that moment and there aren't any. So there is no handler bound to move the elements back.
Also there is no need to use an .each() loop to individually bind .click() to each element in the loop: you can just call .click() directly and it will bind the handler to all elements that matched your selector.
The solution is to use a delegated handler, where you use .on() to bind the click to the parent div elements but supply a secondary selector that jQuery will automatically test at the time the click event occurs:
function tag_ui_move(tag_object,filter_move_to){
$(filter_move_to).append(tag_object).fadeIn();
//$(tag_object).remove(); <-- commented out: don't remove the element,
// because append *moves* it
}
$(document).ready(function(){
var stored_tag = [];
$('[id^="tagbox-"]').on('click', 'span.tag-filter', function(){
tag_ui_move(this,'div[id^="tagfilter-"]');
});
$('div[id^="tagfilter-"]').on('click', 'span', function(){
tag_ui_move(this,'div[id^="tagbox-"]');
});
});
That way, when a click on any element within '[id^="tagbox-"]' occurs, jQuery tests if the target element matches the selector 'span.tag-filter' and if and only if it does it calls your handler function. So then the clicks work on the elements even when they're dynamically moved back and forth between the two parent divs.
Demo: http://jsfiddle.net/6m4aac3k/
HTML
<h4>Video Tags</h4>
<div id="tagbox">
<span class="tag-filter">tag 1</span>
<span class="tag-filter">tag 2</span>
<span class="tag-filter">tag 3</span>
</div>
<h4>Video Filters</h4>
<div id="tagfilter">
</div>
Javascript
function tag_ui_move(tag_object,filter_move_to){
$(filter_move_to).append($(tag_object)).fadeIn();
}
$(document).ready(function(){
$(".tag-filter").click(function(){
var inTagBox=$(this).parent( "#tagbox" ).length>0;
var moveTo=inTagBox ? '#tagfilter' : '#tagbox';
tag_ui_move(this,moveTo);
});
});
JSFiddle
Tag filter
Right now when I click on li, it is highlighted correctly. However, when I click on the checkbox itself, there is no response. How do I highlight/un-highlight the li when clicking on either the li or the checkbox itself?
I also do not wish to adjust this part of my jQuery: $('.rightP').find('ul').on( (because the elements inside the ul are generated dynamically) if possible.
HTML
<div class = "rightP">
<ul>
<li>
<div class="sender">
<span>
<input type="checkbox">
</span>
</div>
<div id=2 class="message">
<p>test</p>
</div>
...
</li>
...
</ul>
...
</div>
JQuery :
deleteIDs = [];
$('.rightP').find('ul').on("click","li",function(event) {
var checkbox = $(this).find("input[type='checkbox']");
if(checkbox.hasClass('open')){
if(!checkbox.prop("checked") ){
checkbox.prop("checked",true);
$(this).css({'background-color':"#EEEEEE"});
$(this).find('div.message').each(function(){
deleteIDs.push($(this).prop('id'));
});
} else {
checkbox.prop("checked",false);
$(this).css({'background-color':"white"});
$(this).find('div.message').each(function(){
var deleteID = $(this).prop('id');
deleteIDs = $.grep(deleteIDs,function(value){
return (value!=deleteID);
});
});
}
}
});
I think if you want handle li click. You must not use check checkbox. You image and change it src to click.png when click and noclick.png when no click. Hope this help!
Ok if you dont want image i mention you my full code no use image, it work ok
<!DOCTYPE html >
<html >
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<div class = "rightP">
<ul>
<li>
<div class="sender">
<span>
<input type="checkbox">
</span>
</div>
<div id=2 class="message">
<p>test</p>
</div>
</li>
</ul>
<script>
deleteIDs = [];
var isnotcheck=true;
var clickcheckbox=false;
$('.rightP').find('ul').on("click","input",function(event) {
clickcheckbox=true;
isnotcheck=!isnotcheck;
});
$('.rightP').find('ul').on("click","li",function(event) {
;
if(!clickcheckbox)
{
isnotcheck=!isnotcheck;
}
var checkbox = $(this).find("input[type='checkbox']");
clickcheckbox=false;
if(!isnotcheck ){
checkbox.prop("checked",true);
$(this).css({'background-color':"#EEEEEE"});
$(this).find('div.message').each(function(){
deleteIDs.push($(this).prop('id'));
});
} else {
//alert(checkbox);
checkbox.prop("checked",false);
$(this).css({'background-color':"white"});
$(this).find('div.message').each(function(){
var deleteID = $(this).prop('id');
deleteIDs = $.grep(deleteIDs,function(value){
return (value!=deleteID);
});
});
}
});
</script>
</div>
</body>
</html>
You look two event. li click and checkbox click , two event occured if you click on checkbox if no one event occured. You can see my variable
var isnotcheck=true;
var clickcheckbox=false;
to know click or not click checkbox.
Hope this help!
Rather than this line
$('.rightP').find('ul').on("click","li",function(event) {
You can try
$('.rightP').on("click","ul li",function(event) {
When you're dealing with generated content you should use deferred event handlers, here's an example using Jquery UI to apply the highlight effect when you click either the checkbox or div.
http://jsbin.com/kibicega/1/
I am trying to create an effect whereby clicking on a title toggles the corresponding content div. Clicking on another title while some content is showing should hide that content div and show the content div corresponding to the title just clicked.
However the code is not doing anything, as you can see on the following jquery: http://jsfiddle.net/dPsrL/
Any ideas?
HTML:
<div class="row title">
<div class="title" industry_id="education">Ed</div>
<div class="title" industry_id="tech">Tech</div>
<div class="title" industry_id="finance">Fin</div>
</div>
<br>
<br>
<div class="row content">
<div class="content" id="education">Education is great</div>
<div class="content" id="tech">Technology is awesome</div>
<div class="content" id="finance">Finance is super</div>
</div>
JAVASCRIPT:
$(document).ready(function () {
$('.content').hide();
});
('.title').on('click', function () {
var clicked = $(this).attr('industry_id');
alert(clicked);
$("#"+clicked).toggle(400);
$("#"+clicked).siblings().hide();
});
Instead of toggling the clicked element first and then hiding the others, why don't you just hide everything first and then show the clicked one? Saves you a check, and all you have to do is switch the order
$('.title').on('click', function () {
var clicked = $(this).attr('industry_id');
alert(clicked);
$('.content').hide();
$('#' + clicked).show(400);
});
Your attribute doesn't have the id selector in it. You need to do a string concatenation :
$('.title').on('click', function () {
var clicked = $(this).attr('industry_id');
alert(clicked);
$('#' + clicked).toggle(400);
$('#' + clicked).siblings().hide();
//The two last lines could be :
//$('#' + clicked).toggle(400).siblings().hide();
});
Also you have to remove the class content and title on the row since it trigger the click event and the hide part.
Here's a working fiddle : http://jsfiddle.net/dPsrL/3/
Typo on ('.title'). Should be $('.title'). Also, you should probably not give the container divs the same class as the child divs and then use that same class in your CSS and jQuery. It just makes selection more difficult.
jsFiddle example
I have four DIVS, one is ready and the other three are still hidden. When the link to the second div is pressed, I want the second div to show up, and so for the next link.
The problem is, all the four DIV doesn't have ID and has the same class.
I just want it to automatically run without knowing what is the ID and the class of the div, or anything inside the div. It may look like a slideshow but on click function.
<p> link to the ready div </P>
<p> link to the second div </P>
<p> link to the third div </P>
<p> link to the last div </P>
<div id="wrapper">
<div> this is the div that is ready. This div has no ID and has the same class with others <div>
<div> this is the second div that is hidden. This div has no ID and has the same class with others <div>
<div> this is the third div that is hidden. This div has no ID and has the same class with others <div>
<div> this is the last div that is hidden. This div has no ID and has the same class with others <div>
</div>
FIDDLE
i have made a fiddle that might suite your case please have a look. You can make some modifications according to your needs.
var currentDiv = 0;
$(document).ready(function(){
$(".container div").click(function(){
$(".container div").eq(currentDiv+1).css( "display", "block" );
currentDiv++;
})
});
JSFIddle Link
Im pretty sure this is what you are looking for.
jQuery
$(".options p").click(function () {
var ourPick = $("p").index(this) + 1;
$(".container div:nth-child(" + ourPick + ")").show();
});
Demo Here
So what we are doing is getting the index for the link pressed and then using that to select the div we want to show (this is using :nth-child()).
Note: I have put a container around the links so you it doesn't pick up every p on the page.
If you want only one at a time you can just set them all to hide before showing one.
jQuery:
$(".options p").click(function () {
var ourPick = $("p").index(this) + 1;
$(".container div").hide();
$(".container div:nth-child(" + ourPick + ")").show();
});
Demo Here
JS FIDDLE DEMO
Explanation
<div class="parentDiv">
<div class="div">1</div>
<div class="div">2</div>
<div class="div">3</div>
<div class="div">4</div>
</div>
<div class="buttons">
<a idx="1">1</a>
<a idx="2">2</a>
<a idx="3">3</a>
<a idx="4">4</a>
</div>
$('.buttons a').click(
function(event)
{
var idx = $(event.target).attr('idx');
$('.div').hide(); //Hides all the divs
$('.parentDiv div:nth-child('+idx+')').show(); // Shows required div
}
);
DISADVANTAGE
If you will insert more contents, there is more work. Else no problem..
If you insert a div , you have to change all the links.
<div class="parentDiv">
<div class="div">1</div>
<div class="div">2.0 Inserted Div</div>
<div class="div">2</div>
<div class="div">3</div>
<div class="div">4</div>
</div>
<div class="buttons">
<a idx="1">1</a>
<a idx="2">2.0</a>
<a idx="3">2</a>
<a idx="4">3</a>
<a idx="5">4</a>
</div>
Not here , All the idx has to be changed. Since my code uses nth-child property
Edited
Updated Fiddle
Another Update
I'm adding a click event to a span that is within a div. The target of this event, which will become visible, is a first div that is within a div, two divs down. How can I traverse the DOM to find it?
Perhaps it'll be clearer with the code:
<div a>
<h2>
<span id="here">Click</span>
</h2>
</div>
<div></div>
<div>
<div class="targetDiv">This is the div we need to find</div>
<div class="targetDiv">There are other divs with the same id, but we don't need to find those</div>
<div class="targetDiv">Not looking for this one </div>
<div class="targetDiv">Or this one either</div>
</div>
I've searched left and right and cannot find an answer. It's important to restrict the event ONLY to the first div immediately after the span.
Any help would be much appreciated.
As shown, the code would look like this:
$('span#here').on('click', function() {
$(this).closest('div').siblings(':contains(.targetDiv)').children().eq(0).show();
}
Here's a sample of the fish we caught
$(function() {
$('#here').on('click', function() {
var div = $(this) //the element clicked
.closest('div') //find nearest parent div
.nextAll(':eq(1)') //find the second next div
.children(':eq(0)') //find the first child of it
.show(); //remove invisible cloak
});
});
This works. I provided an example you can just save to a html file and test it yourself
<style>
.targetDiv{display:none;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#here').click(function(){
$('.targetDiv').first().show(); // or whatever you want
});
});
</script>
<div a>
<h2>
<span id="here">Click</span>
</h2>
</div>
<div></div>
<div>
<div class="targetDiv">This is the div we need to find</div>
<div class="targetDiv">There are other divs with the same id, but we don't need to find those</div>
<div class="targetDiv">Not looking for this one </div>
<div class="targetDiv">Or this one either</div>
</div>