Javascript click specific to ID - javascript

I have a div setup like so:
<div class="content">
<button class="show-comments" id="content1"></button>
</div>
<div class="comments-wrapper" id="comment1"></div>
<div class="content">
<button class="show-comments" id="content2"></button>
</div>
<div class="comments-wrapper" id="comment2"></div>
I have the following code:
$('.show-comments').click(function(e){
e.preventDefault();
$('.comments-wrapper').slideToggle('slow');
});
As you would assume, the code works but on a class basis. I'd like for it to open up only the .comments-wrapper of its associated id (i.e. open slideToggle comments2 if content 2 button is clicked and so on and so on).
How would I do this?

$('.show-comments').click(function(e){
e.preventDefault();
$(this).closest(".content").next('.comments-wrapper').slideToggle('slow');
});
Note that this is dependent on the .content element being immediately followed by the .comments-wrapper.
If you have access to modify the html itself, I would suggest adding a wrapper element and then doing the following to avoid the reliance on the exact order of elements:
<div class="wrapper">
<div class="content">
<button class="show-comments" id="content1"></button>
</div>
<div class="comments-wrapper" id="comment1"></div>
</div>
<div class="wrapper">
<div class="content">
<button class="show-comments" id="content2"></button>
</div>
<div class="comments-wrapper" id="comment2"></div>
</div>
$(this).closest(".wrapper").find('.comments-wrapper').slideToggle('slow');
This way, if you add an element between the .content and the .comments-wrapper it does not break the code.

You can do this:
$(this).parent("div").next('.comments-wrapper').slideToggle('slow');
This will find the related div of class .comments-wrapper and slide toggle.
And a fiddle: http://jsfiddle.net/xCJQB/

$('.show-comments').click(function (e) {
e.preventDefault();
var num = this.id.match(/\d+$/)[0];
$("#comment" + num).slideToggle('slow');
});
Demo ---> http://jsfiddle.net/7pkyk/1/

Use this context
$(this).closest('.comments').next('.comments-wrapper').slideToggle('slow');
If it is not the immediate element then you might try this as well
$(this).closest('.comments')
.nextAll('.comments-wrapper').first().slideToggle('slow');

you can add a common class to associate a button with a div.
html:
<div class="content">
<button class="show-comments group1" id="content1"></button>
</div>
<div class="comments-wrapper group1" id="comment1">1</div>
<div class="content">
<button class="show-comments group2" id="content2"></button>
</div>
<div class="comments-wrapper group2" id="comment2">2</div>
javascript:
$('.show-comments').click(function(e){
var associate = $(this).attr('class').match(/group\d+/).pop();
var selector = '.comments-wrapper.' + associate;
e.preventDefault();
$(selector).slideToggle('slow');
});
http://jsfiddle.net/uMNfJ/

Related

Find the index of a div inside a container

I have a container with multiple divs and in each div I have a handler on which you can click.
The requirement is to return the index of the div in the container for further processing.
I've simplified the code for readability purposes.
The HTML:
<div class="container">
<div class="block">
<div class="handler">
Click
</div>
</div>
<div class="block">
<div class="handler">
Click
</div>
</div>
<div class="block">
<div class="handler">
Click
</div>
</div>
<div class="block">
<div class="handler">
Click
</div>
</div>
</div>
The Javascript code I tried so far but I always get -1 as the index:
$(document).ready(function(){
$('.handler').click(function(e) {
let index = Array.prototype.indexOf.call($('.container'), $(this).parents('.block'));
console.log(index);
});
});
I also created a fiddle.
So what am I doing wrong here?
You can do the following,
$('.handler').click(function(e) {
var el = e.target;
console.log([].indexOf.call(el.parentNode.parentNode.children, el.parentNode));
});
However if you want to know what was wrong in your code,
Array.prototype.indexOf.call($('.container')[0].children, $(this).parents('.block')[0])
This part should fix the problem in your code. You have been doing it all right, but for the parameter of indexOf we needed the children array of .container and clicked element.
You were passing the container element and current clicked element as an array. That is Array.prototype.indexOf.call('[Container Element]', ['current clicked div']) Which is not right. You should pass something like this,
Array.prototype.indexOf.call('[children, children, children...]', 'current clicked div element').
It was happening because the $('.container') returns an array with the element having a class name .container. But we needed all the children array of the element that contains container class.
And $(this).parents('.block') returns an array with the matching elements even if it is only one.
You can access the index using the index method on parent element of selection.
$(document).ready(function(){
$('.handler').click(function(e) {
console.log($(this).parent().index())
});
});
You can do that like this. Find the index of the closest element of the clicked element, which is also a direct child of .handler. To find index, use index().
$(document).ready(function() {
$('.handler').click(function(e) {
let index = $(this).closest('.block').index()
console.log(index);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="block">
<div class="handler">
Click
</div>
</div>
<div class="block">
<div class="handler">
Click
</div>
</div>
<div class="block">
<div class="handler">
Click
</div>
</div>
<div class="block">
<div class="handler">
Click
</div>
</div>
</div>
You're checking at the wrong level of nesting in your HTML. I believe what you're trying to do is check from one level higher, at ".container" and get the index of the ".block" element that was clicked.
This code works in your Fiddle:
$(document).ready(function(){
$('.handler').click(function(e) {
const p = e.target.parentElement.parentElement;
const index = Array.prototype.indexOf.call(p.children, e.target.parentElement);
console.log(p.className) // "container"
console.log(index)
});
});
This can be done simply using delegate in jQuery.
I modify your JSFiddle code.
$(".container").delegate('.block', 'click', function () {
console.log( $(this).index() );
})
u can use a id
<div class="container">
<div class="block">
<div id='0' class="handler">
Click
</div>
</div>
<div class="block">
<div id='1' class="handler">
Click
</div>
</div>
<div class="block">
<div id='2' class="handler">
Click
</div>
</div>
<div class="block">
<div id='3' class="handler">
Click
</div>
</div>
</div>
$(document).ready(function(){
$('.handler').click(function(e) {
let index = this.id
console.log(index);
});
});
https://jsfiddle.net/vhrt596x/2/

Link simillary name classes so that when one is clicked the other is given a class

Basically, I'm asking for a way to optimize this code. I'd like to cut it down to a few lines because it does the same thing for every click bind.
$("#arch-of-triumph-button").click(function(){
$("#arch-of-triumph-info").addClass("active-info")
});
$("#romanian-athenaeum-button").click(function(){
$("#romanian-athenaeum-info").addClass("active-info")
});
$("#palace-of-parliament-button").click(function(){
$("#palace-of-parliament-info").addClass("active-info")
});
Is there a way to maybe store "arch-of-triumph", "romanian-athenaeum", "palace-of-parliament" into an array and pull them out into a click bind? I'm thinking some concatenation maybe?
$("+landmarkName+-button").click(function(){
$("+landmarkName+-info").addClass("active-info")
});
Is something like this even possible?
Thanks in advance for all your answers.
EDIT: Here's the full HTML.
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Arch of Triumph</span>
</div>
<div class="landmark-button" id="arch-of-triumph-button"></div>
</div>
</div>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Romanian Athenaeum</span>
</div>
<div class="landmark-button" id="romanian-athenaeum-button"></div>
</div>
</div>
----------------------------------------------------------
<div class="landmarks-info-wrapper">
<div class="landmark-info" id="arch-of-triumph-info">
<div class="info-landmark section">
<span class="landmark-title">Arch of Triumph</span>
<span class="landmark-coord">44°28′1.99″N 26°4′41.06″E</span>
</div>
</div>
<div class="landmark-info" id="romanian-athenaeum-info">
<div class="info-landmark section">
<span class="landmark-title">The Romanian Athenaeum</span>
<span class="landmark-coord">44.4413°N 26.0973°E</span>
</div>
</div>
Assuming you're not able to modify your HTML markup (in which case with use of CSS classes would be cleaner), a solution to your question would be as shown below:
// Assign same click handler to all buttons
$("#arch-of-triumph-button, #romanian-athenaeum-button, #palace-of-parliament-button")
.click(function() {
// Extract id of clicked button
const id = $(this).attr("id");
// Obtain corresponding info selector from clicked button id by replacing
// last occurrence of "button" pattern with info.
const infoSelector = "#" + id.replace(/button$/gi, "info");
// Add active-info class to selected info element
$(infoSelector).addClass("active-info");
});
Because each .landmark-button looks to be in the same order as its related .landmark-info, you can put both collections into an array, and then when one is clicked, just find the element with the same index in the other array:
const buttons = [...$('.landmark-button')];
const infos = [...$('.landmark-info')];
$(".landmark-button").click(function() {
const i = buttons.indexOf(this);
$(infos[i]).addClass('active-info');
});
This does not rely on IDs at all - feel free to completely remove those from your HTML to declutter, because they don't serve any purpose now that they aren't being used as selectors.
Live snippet:
const buttons = [...$('.landmark-button')];
const infos = [...$('.landmark-info')];
$(".landmark-button").click(function() {
const i = buttons.indexOf(this);
$(infos[i]).addClass('active-info');
});
.active-info {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Arch of Triumph</span>
</div>
<div class="landmark-button" id="arch-of-triumph-button">click</div>
</div>
</div>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Romanian Athenaeum</span>
</div>
<div class="landmark-button" id="romanian-athenaeum-button">click</div>
</div>
</div>
----------------------------------------------------------
<div class="landmarks-info-wrapper">
<div class="landmark-info" id="arch-of-triumph-info">
<div class="info-landmark section">
<span class="landmark-title">Arch of Triumph</span>
<span class="landmark-coord">44°28′1.99″N 26°4′41.06″E</span>
</div>
</div>
<div class="landmark-info" id="romanian-athenaeum-info">
<div class="info-landmark section">
<span class="landmark-title">The Romanian Athenaeum</span>
<span class="landmark-coord">44.4413°N 26.0973°E</span>
</div>
</div>
Older answer, without knowing the HTML: You can extract the ID of the clicked button, slice off the button part of it, and then select it concatenated with -info:
$(".landmark-button").click(function() {
const infoSel = this.id.slice(0, this.id.length - 6) + 'info';
$(infoSel).addClass('active-info');
});
A much more elegant solution would probably be possible given the HTML, though.

if one item is clicked, remove the other items?

I'm learning Javascript and jQuery and I'm stuck at this one problem. Let's say my code looks like this:
<div id="hey"> hey </div>
<div id="how"> how </div>
<div id="are"> are </div>
<div id="you"> you </div>
Now, if i click one of the div's, i want the other ones to disappear.
I know, I could create 4 functions for each one of them with on.click hey and display none with how , are and you. But is there a easier way? I bet there is, with classes maybe?
Thanks for responding!
Use siblings to get reference to its "brothers".
Given a jQuery object that represents a set of DOM elements, the .siblings() method allows us to search through the siblings of these elements in the DOM tree and construct a new jQuery object from the matching elements.
$('div').click(function(){
$(this).siblings().hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hey"> hey </div>
<div id="how"> how </div>
<div id="are"> are </div>
<div id="you"> you </div>
Or you can hide all the other div which not the clicked element using not
Remove elements from the set of matched elements.
$('div').click(function() {
$('div').not(this).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hey"> hey </div>
<div id="how"> how </div>
<div id="are"> are </div>
<div id="you"> you </div>
You can just hide siblings() of clicked div.
$('div').click(function() {
$(this).siblings().fadeOut()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hey">hey</div>
<div id="how">how</div>
<div id="are">are</div>
<div id="you">you</div>
Yeah there are some easier ways and I could tell a one from it,
Set a common class to all the elements that you are gonna target,
<div class="clickable" id="hey"> hey </div>
<div class="clickable" id="how"> how </div>
<div class="clickable" id="are"> are </div>
<div class="clickable" id="you"> you </div>
And you have to bind a single click event by using a class selector,
$(".clickable").on("click", function(){ });
Now use the .siblings() functions to hide the required elements,
$(".clickable").on("click", function(){
$(this).siblings(".clickable").hide();
});
But using a toggle instead of hide would sounds logical,
$(".clickable").on("click", function(){
$(this).siblings(".clickable").toggle();
});
Since you can do the same operation over all the elements.
You can use not to avoid element and this will indicate current instance.
$(document).ready(function(){
$("div").on("click",function(){
$("div").not(this).hide("slow");
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hey"> hey </div>
<div id="how"> how </div>
<div id="are"> are </div>
<div id="you"> you </div>
Assign a class to each of the elements:
<div id="hey" class='sth'> hey </div>
<div id="how" class='sth'> how </div>
<div id="are" class='sth'> are </div>
<div id="you"class='sth' > you </div>
And write a js function onclick.
Remove class 'sth' from 'this' element in this function
Hide all elements with class 'sth' $('.sth').hide();
For this example - you don't need to add any further selectors to target the div's although in reality - this solution wwould cause all divs on the page to be affectecd - adding classes would be my actual suggestion: - but this works for this example. Click a div and all divs are hidden then the clicked one is shown. I also added a reset button to allow all divs to reappear.
$('div').click(function(){
$('div').hide();
$(this).show();
});
$('#reset').click(function(){
$('div').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hey"> hey </div>
<div id="how"> how </div>
<div id="are"> are </div>
<div id="you"> you </div>
<hr/>
<button type="button" id="reset">Reset</button>
$(document).ready(function(){
$("div").on("click",function(){
$("div").not(this).toggle("slow");
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hey"> hey </div>
<div id="how"> how </div>
<div id="are"> are </div>
<div id="you"> you </div>

jquery clone a link (once per div)

I have a set of divs, and need to clone the link from the top and insert into the last div (mobile-link). It is either cloning the links from all of the divs, and then inserting all of them at once, or if I use :eq(0), it's putting the first link into all of the divs.
<div class="course">Accounting</div>
<div class="start-date">1-1-2017</div>
<div class="credits">4</div>
<div class="location">Online</div>
<div class="mobile-link"></div>
<div class="course">Business</div>
<div class="start-date">1-1-2017</div>
<div class="credits">3</div>
<div class="location">Online/Campus</div>
<div class="mobile-link"></div>
<script>
$(".course a:eq(0)").clone().appendTo(".mobile-link");
</script>
What do I need to change to make this work properly?
You need to process each anchor separately:
$(".course").each(function() {
var myLink = $(this).find('a').clone();
$(this).nextAll('.mobile-link').first().append(myLink);
});
Demo fiddle
Append method can take a function as argument, and here it is appending to the each .mobile-link first <a> from his previous .course div
$(".mobile-link").append(function(){
return $(this).prevAll('.course:first').find('a:first').clone();
});
Check the below snippet
$(".mobile-link").append(function(i) {
return $(this).prevAll('.course:first').find('a:first').clone();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="course">Accounting
</div>
<div class="start-date">1-1-2017</div>
<div class="credits">4</div>
<div class="location">Online</div>
<div class="mobile-link"></div>
<div class="course">Business
</div>
<div class="start-date">1-1-2017</div>
<div class="credits">3</div>
<div class="location">Online/Campus</div>
<div class="mobile-link"></div>
I beleive that you should use last (If I understood question correctly):
var lastDiv = $(".mobile-link").last();
$(".course a:eq(0)").clone().appendTo(lastDiv);
Here is jsfiddle: fiddle

Jquery div expands all divs on page

<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(".content").hide();
jQuery(".link").click(function()
{
jQuery("div.content").slideToggle(500);
});;
});
</script>
How to expand only the div which is linked to the specific link?
Edit:
Its done like this
<div class="comment">
<div class="bar">
<a class="link">#</a>
</div>
</div>
<div class="content">
<div class="comment">
<div class="bar">
<a class="link">#</a>
</div>
</div>
</div>
EDIT 2:
You changed your HTML. Now do this:
jQuery(this).closest('div.comment').next('div.content').slideToggle(500);
But wait! Now you have 2 different div.link elements in different relation to .content elements. Is this your actual HTML markup?
You could also do this:
jQuery(this).closest('div.content').slideToggle(500);
Please provide your actual HTML.
EDIT:
Based on updated question, do this:
jQuery(this).parents('div.blaat1').eq(1).next().slideToggle(500);
How to expand only the div which is linked to the specific link?
How are they linked?
If the div is a descendant, do this:
jQuery(this).find('div.content').slideToggle(500);
If the div is a an ancestor, do this:
jQuery(this).closest('div.content').slideToggle(500);
If the div is the next sibling, do this:
jQuery(this).next().slideToggle(500);
If the div is the previous sibling, do this:
jQuery(this).prev().slideToggle(500);
Without seeing your HTML structure, we can only guess at the solution.
For this HTML:
<div class="blaat1">
<div class="blaat1">
<a class="link">#</a>
</div>
<div class="blaat2">
<a class="link">#</a>
</div
</div>
<div class="content">
<div class="otherdivs">
<div class="blaat1_div"><p>Hi – I'm blaat 1</p></div>
<div class="blaat2_div"><p>Hi – I'm blaat 2</p></div>
</div>
</div>
Use this JS:
<script type="text/javascript">
$(document).ready(function() {
$(".content").hide();
$(".link").click(function() {
var blaat = $(this).parent().attr("class");
$(blaat+"_div").slideToggle(500);
});;
});
</script>
I haven't tested that, but it should work.
Try this:
$(".link").click(function(){
$(this).parents('div.content').slideToggle(500);
});;

Categories

Resources