Getting the selector, not the handler - javascript

HTML:
<div id="div1">
<div class="close">close</div>
</div>
<div id="div2">
<div class="close">close</div>
</div>
jQuery:
$('.close').on('click', '#div1, #div2', function(){
console.log ( $(this) ); // .close
});
If I have multiple elements with close buttons, how do I get the parent element as this and not the button?
So if I click the .close on #div1, I need #div1 as this to work with it.

By instinct, I would look to closest, which takes a selector as a param:
var selector = '#div1, #div2';
$('.close').on('click', selector, function(){
console.log ( $(this).closest(selector) ); // .close
});
.closest will return a jQuery object representing first node that matches the selector. It starts with the current object and continues to .parent() until it finds a match

since the element is a child of the element you want to reference, use a parent selector.
$(this).parent().hide()
Most of the time we would use a class on the element and use closest to select it.
$(this).closest('.msg').hide()
$('.close').on('click', function(){
$(this).closest(".msg").hide();
});
.msg{
.border: 1px solid black
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1" class="msg">
<div class="close">close</div>
<p>test 1</p>
</div>
<div id="div2" class="msg">
<div class="close">close</div>
<p>test 2</p>
</div>

You actually don't need any selector, just a .closest("div").
If you want to be a bit more specific like "The closest ID starts with div" than you could do like:
$('.close').on('click', function(){
$(this).closest("[id^='div']").fadeOut();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">
<div class="close">close1</div>
</div>
<div id="div2">
<div class="close">close2</div>
</div>
Or, by doing it the way you started you could use the event.delegateTarget -
which refers to the actual selector-delegators $('#div1, #div2')
$('#div1, #div2').on('click', '.close', function(event) {
$(event.delegateTarget).fadeOut();
});
// or use also for brevity:
// $("[id^='div']").on(...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">
<div class="close">close1</div>
</div>
<div id="div2">
<div class="close">close2</div>
</div>

Related

How can i click and just own class can be shown on Javascript

<div class="item text-center">
<div class="class1"> <p> Something </p> </div>
</div>
<div class="item text-center">
<div class="class1"> <p> Something </p> </div>
</div>
$(".class1").hide();
$(".item").click(function () {
$(".class1").show();
})
I want that when the user click div of item, its own class1 should be show();
But in my codes, when the user click item of div, all class1 shows.
How can i do that just own class can be shown?
To fix this you need to use DOM traversal to access the .class1 element(s) within the clicked .item. To do that you can use the this keyword within the event handler to access the element which raised the event. Try this:
$(".item").click(function() {
$(this).find(".class1").show();
})
.class1 { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item text-center">
Foo
<div class="class1">
<p> Something </p>
</div>
</div>
<div class="item text-center">
Bar
<div class="class1">
<p> Something </p>
</div>
</div>
Note in the example that I used CSS to hide the .class1 elements instead of JS. This is because JS runs after the DOM has loaded, so can result in elements being visible for a short time before they are hidden. CSS runs before this, so avoids that occurrence.
$(".class1").hide();
$(".item").click(function () {
$(this).find(".class1").show();
});
<!--The parent divs should not be empty, otherwise when later in the code you call the .hide () method on their respective child divs, there would be nothing left to click on-->
<div class="item text-center">
item1
<div class="class1">
<p> Something </p>
</div>
</div>
<div class="item text-center">
item2
<div class="class1">
<p> Something </p>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can use the find () method, the find () method returns the descendant elements of the selected element. Like the code above

jQuery onclick in for each selector

When I click a button div, I want to add a class named active to the popup div that has the corresponding class name in the data-trigger attribute.
For example if I click on the div with class name button-two, the div with data-trigger="button-two" should get class active.
The issue: active is added only to the last popup div. How can I make this work?
Here's what I have tried:
$('.popup').each(function() {
popupObj = $(this);
var popupTrigger = popupObj.data("trigger");
$('.' + popupTrigger).click(function() {
popupObj.addClass('active');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button-one">Test 1</div>
<div class="button-two">Test 2</div>
<div class="button-three">Test 3</div>
<div class="popup" data-trigger="button-one">Hello world</div>
<div class="popup" data-trigger="button-two">Hello there</div>
<div class="popup" data-trigger="button-three">Hello again</div>
This is because you did not declare popupObj as a local variable; It is global, and so it will have changed in the last iteration of the each: it is that value that will be referenced in all three click handlers.
Remember that each will have performed all iterations before any of the click handlers get called.
Solution: use var popupObj. That way each of the click handlers will reference their "own" variable.
Simple way to use data attribute also for buttons .. and make only one click event for the buttons .. see the next example
$('.button[data-to-trigger]').on('click' , function(){
var GetTriggerDiv = $(this).attr('data-to-trigger');
$('.popup').removeClass('active').filter('.popup[data-trigger="'+GetTriggerDiv+'"]').addClass('active');
});
.active{
background : red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="button" data-to-trigger="button-one">Test 1</div>
<div class="button" data-to-trigger="button-two">Test 2</div>
<div class="button" data-to-trigger="button-three">Test 3</div>
<div class="popup" data-trigger="button-one">Hello world</div>
<div class="popup" data-trigger="button-two">Hello there</div>
<div class="popup" data-trigger="button-three">Hello again</div>
The "each" function in jQuery returns 2 values: index and element. Try using the element returned instead of $(this).
$('.popup').each(function(index, element) {
var popupTrigger = element.data("trigger");
$('.'+popupTrigger).click(function() {
element.addClass('active');
});
});
Here's a solution that matches the popup to the button using the same data trigger for both:
$(document).ready(function() {
$(".btn").click(function() {
var trigger = $(this).data("trigger");
$('.popup').each(function() {
if ($(this).data("trigger") == trigger) {
$(this).addClass('active');
} else {
$(this).removeClass('active');
}
});
});
});
.active {
background-color: coral;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn" data-trigger="button-one">Test 1</div>
<div class="btn" data-trigger="button-two">Test 2</div>
<div class="btn" data-trigger="button-three">Test 3</div>
<div class="popup" data-trigger="button-one">Hello world</div>
<div class="popup" data-trigger="button-two">Hello there</div>
<div class="popup" data-trigger="button-three">Hello again</div>

Selecting a parent class from a child class when there are multiple div's of same parent class

There are four parent div's with same class and all of them have a child with class 'child'. Now the question is, Let's say I click on the First parent div's Child div(First Child) and I want to have some effect on it's parent i.e 'First Parent' to be effected only. Due to being similar class' all parent div's will be effected.
Here's the HTML
<div class="parent"> //First Parent
<div class="child"></div> //First Child
</div>
<div class="parent">
<div class="child"></div>
</div>
<div class="parent">
<div class="child"></div>
</div>
<div class="parent">
<div class="child"></div>
</div>
Here's the JQuery
$('.child').on('click',function(){
$(this).parent('.parent').css({
'display':'none';
});
});
Clicking on child element will effect all parent div's with class "parent". Either I can give them all separate classes then write onClick() method for all of them but that is not a proper solution.
You can do
$(this).parent().hide();
if you want to hide the parent of the clicked div
Use closest('.class')
$('.child').click(function() {
$(this).closest('.parent').css('display':'none');
});
I Updated my answer !
Your answer is correct and a good practice, I don't see what the issue here is.
The only change you could do $(this).parent('.parent').hide(); instead of using the jQuery css method.
try this code
$(document).ready(function() {
$('.child').click(function() {
$(this).parent().css('display', 'none');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<div class="child">first</div>
</div>
<div class="parent">
<div class="child">second</div>
</div>
<div class="parent">
<div class="child">third</div>
</div>
<div class="parent">
<div class="child">fourth</div>
</div>
$('.child').on('click',function(){
$(this).closest('.parent').css({
'display':'none'
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent"> //First Parent
<div class="child">div 1</div> //First Child
</div>
<div class="parent">
<div class="child">div 2</div>
</div>
<div class="parent">
<div class="child">div 3</div>
</div>
<div class="parent">
<div class="child">div 4</div>
</div>
alterate your JS as follow:
$('.child').on('click',function(){
$(this).parent().css({
'display':'none'
});
});
For me, on click of a div, it hides its parent. Not others.
By the way, you had a ";" after 'none' which is invalid as this is a object, and accepts only either nothing or a comma.
see https://jsfiddle.net/n66sdgdz/
Okay, so lots of answers here with "try this" or other examples.
First off, your code actually works, as you can see here:
Fiddle
However, there was one error in you code. This being the ; at the end of your 'display':'none';
There should be no ; inside a javascript object.
$(document).ready(function() {
$('.child').on('click',function(){
$(this).closest('.parent').css('display','none');
});
});
OR
$('.child').on('click',function(){
$(this).parent('.parent').eq(0).css('display','none');
});
https://jsfiddle.net/t9wxbLs8/

Can't traverse the DOM with next

I have the following markup
<a class="list-group-item" href="#">
<div class='row'>
<div class='col-xs-10 shows-submenu'>
<h4 class="list-group-item-heading">A title</h4>
</div>
</div>
</a>
<div class='list-group-item hidden-group-item hide'>
<div class="row">
<div class="col-sm-12">
<p class="list-group-item-text">
Some text
</p>
</div>
</div>
</div>
I'd like to remove the 'hide' class in the 'hidden-group-item' when I click the 'shows-submenu'.
I was trying to do it with the following jQuery
$(function(){
$('body').on('click', '.shows-submenu', function() {
if ($(this).next('.hidden-group-item').hasClass('hide')) {
$('.hidden-group-item').addClass('hide');
$(this).next('.hidden-group-item').toggleClass('hide');
}
else {
$(this).next('.hidden-group-item').toggleClass('hide');
}
$('.hidden-form-item').addClass('hide');
});
});
but I can't make it work. The next() method seems to work only if the 'shows-submenu' class is added to the whole a tag but not in the col-xs-10 div where I want it to be.
Could you figure out why is this not working?
Thanks
div.hidden-group-item is not a sibling of .shows-submenu element thus .next() will not work.
You can use .closest() to traverse up ancestor and then use .next()
var hiddenDiv = $(this).closest('a.list-group-item').next('.hidden-group-item');
You code can also be improved.
$(function() {
$(document).on('click', '.shows-submenu', function() {
var hiddenDiv = $(this).closest('a.list-group-item').next('.hidden-group-item');
$('.hidden-form-item').not(this).addClass('hide');
hiddenDiv.toggleClass('hide');
});
});
.hide {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="list-group-item" href="#">
<div class='row'>
<div class='col-xs-10 shows-submenu'>
<h4 class="list-group-item-heading">A title</h4>
</div>
</div>
</a>
<div class='list-group-item hidden-group-item hide'>
<div class="row">
<div class="col-sm-12">
<p class="list-group-item-text">
Some text
</p>
</div>
</div>
</div>
Replace the following:
$(this).next('.hidden-group-item')
with
$(this).closest('a').next('.hidden-group-item')
and try again.
Explanation: next() get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
And hidden-group-item is not the sibling in your html.
Try this:
$('body').on('click', '.shows-submenu', function() {
if ($(this).closest(".list-group-item").next('.hidden-group-item').hasClass('hide')) ......
next() method will only work in siblings.
use find() method instead like this.
$.find('.hidden-group-item').toggleClass('hide');

Hiding an element through DOM traversal

What if it has few parents? (as in grandparents, great grandparents)
<div class="lvl1">
<div class="lvl1.1">
<div class="lvl1.2">
<button class="btn-submit">Click Me</button>
<div class="a1">Hello
<div>
</div>
</div>
<div class="lvl2">
<div class="b1">
<div class="b2">Make me disappear!</div>
</div>
</div>
<div class="lvl3">
<div class="c1">Thank you.
</div>
</div>
JS
$(function(){
$(".btn-submit").click(function() {
$(this).parent(".lvl1").siblings(".lvl2").children(".b2").hide();
});
});
How to use .parent, .parents, .siblings, .children, .next, .prev to show and hide the div?
If I assume that you have that structure repeated and want to remove the one in the same copy as the .btn_submit that was clicked, we go up to the .lvl1 via closest, over to the .lvl2 via .nextAll().first() (or we could just use .next), and then .find the .b2 in there:
$(".btn-submit").click(function() {
$(this).closest(".lvl1").nextAll(".lvl2").first().find(".b2").hide();
});
Your code is very close, just two things that I had to change:
Instead of using .siblings(".lvl2"), which will find all of them, I used .nextAll(".lvl2").first() to just find the one immediately after "this" .lvl1.
I used find instead of children, because children will only go down one level (direct child), not search descendants
I also used closest(".lvl1") so that if you move the .btn_submit deeper into .lvl1, it will continue working.
Live Example:
$(function() {
$(".btn-submit").click(function() {
$(this)
.closest(".lvl1")
.nextAll(".lvl2")
.first()
.find(".b2")
.hide();
});
});
<div class="lvl1">
<button class="btn-submit">Click Me</button>
<div class="a1">Hello
</div>
</div>
<div class="lvl2">
<div class="b1">
<div class="b2">Make me disappear!</div>
</div>
</div>
<div class="lvl3">
<div class="c1">Thank you.
</div>
</div>
<div class="lvl1">
<button class="btn-submit">Click Me</button>
<div class="a1">Hello
</div>
</div>
<div class="lvl2">
<div class="b1">
<div class="b2">Make me disappear!</div>
</div>
</div>
<div class="lvl3">
<div class="c1">Thank you.
</div>
</div>
<div class="lvl1">
<button class="btn-submit">Click Me</button>
<div class="a1">Hello
</div>
</div>
<div class="lvl2">
<div class="b1">
<div class="b2">Make me disappear!</div>
</div>
</div>
<div class="lvl3">
<div class="c1">Thank you.
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
there is possible to disappear div directly using,
$(".b2").hide();
but if you want to use ".parent, .parents, .siblings, .children, .next, .prev",
$(".btn-submit").parent().siblings(".lvl2").children().children(".b2").hide();
need to you children() Two times... because .b2 is not directly child to .lvl2,
another best way to hide ".b2" is,
$(".btn-submit").parent().siblings(".lvl2").find(".b2").hide();
so your Ans is:
$(".btn-submit").click(function() {
$(".btn-submit").parent().siblings(".lvl2").find(".b2").hide();
});
.children selects the children and not descendants of the element. You just need to replace the .children with the .find method and your code will select the target element.

Categories