Targeting Multiple Elements with One Function - javascript

I have a function that assigns dynamic classes to my div's. This function is a that runs on the page. After the page loads, all 10 of my primary 's have classes ".info1" or ".info2" etc...
I am trying to write a Jquery function that changes the class of the div you click on, and only that one. Here is what I have attempted:
$(".info" + (i ++)).click(function(){
$(".redditPost").toggleClass("show")
});
I have also tried:
$(".info" + (1 + 1)).click(function(){
$(".redditPost").toggleClass("show")
});
And
$(".info" + (i + 1)).click(function(){
$(".redditPost").toggleClass("show")
});
EDITED MY HTML: DIV RedditPost is actually a sibling to Info's parent
<div class="listrow news">
<div class="newscontainer read">
<div class=".info1"></div>
<div class="redditThumbnail"></div>
<div class="articleheader read">
</div>
<div class="redditPost mediumtext"></div>
</div>
My issue is two fold.
The variable selection for ".info" 1 - 10 isn't working because i doesn't have a value.
If I did target the correct element it would change all ".redditPost" classes instead of just targeting the nearest div.

Try like this.
$("[class^='info']").click(funtion(){
$(this).parent().find('.redditPost').toggleClass("show");
});
Alternative:
$('.listrow').each(function(){
var trigger = $(this).find("[class^='info']");
var target = $(this).find('.redditPost');
trigger.click(function(){
target.toggleClass("show");
});
});

Try this
$("div[class*='info']").click(function(){
$(this).parent().find(".redditPost").toggleClass("show")
});
Explanation:
$("div[class*='info'])
Handles click for every div with a class containing the string 'info'
$(this).parent().find(".redditPost")
Gets the redditPost class of the current clicked div

Since the class attribute can have several classes separated by spaces, you want to use the .filter() method with a RegEx to narrow down the element selection as follows:
$('div[class*="info"]').filter(function() {
return /\binfo\d+\b/g.test( $(this).attr('class') );
}).on('click', function() {
$(this).siblings('.redditPost').toggleClass('show');
});
.show {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="listrow news">
<div class="newscontainer read">
<div class="info1">1</div>
<div class="redditThumbnailinfo">2</div>
<div class="articleheader read">3</div>
<div class="redditPost mediumtext">4</div>
</div>
</div>

Related

toggle div using for loops

just wondering what went wrong.. i have two div named click_1 and click_2.. and i want to toggle the div named hide corresponding with their numbers.. lets say click_1 with hide_1 and click_2 with hide_2.. but when i ran the code only click_1 is functioning .. what seems to be wrong... newbie here.. recently learned jquery
<div id='click_1'>
<div id='hide_1'></div>
</div>
<div id='click_2'>
<div id='hide_2'></div>
</div>
<script>
function toggle_div(id_A,id_B){
for(var i=0; i<3; i++){
var new_A = id_A + i;
var new_B = id_B + i;
$(new_A).click(function(){
$(new_B).toggle();
});
}
}
toggle_div('click_','hide_');
</script>
The issue is because your id selectors are missing the # prefix:
toggle_div('#click_', '#hide_');
However you should note that you will also need to use a closure for this pattern to work otherwise the new_B element will always be the last one referenced in the for loop.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='click_1'>
click 1
<div id='hide_1'>hide 1</div>
</div>
<div id='click_2'>
click 2
<div id='hide_2'>hide 2</div>
</div>
<script>
function toggle_div(id_A, id_B) {
for (var i = 1; i < 3; i++) {
var new_A = id_A + i;
var new_B = id_B + i;
(function(a, b) {
$(a).click(function() {
$(b).toggle();
})
})(new_A, new_B);
}
}
toggle_div('#click_', '#hide_');
</script>
As you can see this is very verbose, rather complicated and hardly extensible. A much better approach is to use generic classes and DOM traversal to repeat the same logic on common HTML structures.
To achieve this put common classes on the elements to be clicked and the elements to toggle. Then in the single click event handler you can use the this keyword to reference the element which was clicked, then find() the element to toggle within that. Something like this:
$(function() {
$('.click').click(function() {
$(this).find('.hide').toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="click">
click 1
<div class="hide">hide 1</div>
</div>
<div class="click">
click 2
<div class="hide">hide 2</div>
</div>
<div class="click">
click 3
<div class="hide">hide 3</div>
</div>
Also note that this pattern means that you can have an infinite number of .click elements with matching .hide content without ever needing to update your JS code.
It is better not to use for loop for click event ! If you have id like that your can handle by that clicked id split ....
$("[id^='click_']").on("click",function () {
$('#hide_'+this.id.split('_')[1]).toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='click_1'>
Click1
<div id='hide_1'>hide1</div>
</div>
<div id='click_2'>
Click2
<div id='hide_2'>hide2</div>
</div>

toggling div and adding and removing class

i have some divs i wanna toggle i am able to toggle but unable to remove classes when ever i click on the next div
index.php
<div id="menu_top1" class="menu_top1">LINK 1</div>
<div id="menu_top" class="menu_top">LINK 2</div>
<div id="content_area1" style="display:none;">
THIS IS LINK 1
</div>
<div id="content_area2" style="display:none;">
THIS IS LINK 2
</div>
Jquery.js
$('#menu_top1').click(function() {
$('#content_area1').toggle('slow', function() {
$('.menu_top1').toggleClass('active');
});
});
Here is a Fiddle https://fiddle.jshell.net/kunz/t5u6mcmn/
if you are trying to show corresponding content_area when you click on link and make the link active? you can check this
fiddle
i saw you using same id for multiple elements.just edited them.
still you want same id for all elements(strictly not recommended) check this fiddle
check this updated fiddle
$('.menu_top').click(function() {
var index = $( this ).index() + 1;
console.log(index);
$('[id^="content_area"]' ).hide();
$('#content_area' + index ).toggle('slow', function() {
$('.menu_top').toggleClass('active');
});
});

Determining which element was clicked and conditionally choosing which method to call

I am attempting to use JQuery to make 3 thumbnails into buttons that each open up their own page element with details regarding the picture.
Right now I have succeeded in making it so that any thumbnail causes a page element (of the class "description") to scroll open and closed when any thumbnail (from the class "thumbnail") is clicked.
How do I check which thumbnail is clicked on so that I can open a different description corresponding to that specific thumbnail? (This is what I was attempting to do with the "select").
var main = function() {
$('.thumbnail').click(function(select) {
var description = $('.game-descriptions').children('.description');
if( description.is(":hidden")) {
description.slideDown("slow");
}
else
description.hide();
});
}
$(document).ready(main);
Use a data attribute to specify what the thumbnail click is targeting, example: data-target="#game-1", add IDs to your descriptions that match and use data() to use the attribute value of #game-1 a jQuery selector.
Here is a demo
JS
$('.thumbnail').click(function() {
var gameId = $(this).data('target');
$(gameId).slideToggle().siblings(':visible').slideToggle();
});
HTML
<img class="thumbnail" data-target="#game-1" />
<img class="thumbnail" data-target="#game-2" />
<div class="game-descriptions">
<div id="game-1" class="description"></div>
<div id="game-2" class="description"></div>
</div>
Any toggling like toggle(), slideToggle(), fadeToggle() handles the is hidden or is visible
jsFiddle
The parameter to the click function is a jQuery event object, which can be useful in adding some event handling logic. However, within the context of the handler, this refers to the element which triggered the click event, and is typically sufficient for any targeted logic.
Assuming the thumbnails and descriptions have similarly named IDs, for example, you can do something like this:
$(function () {
$('.thumbnail').click(function (event) {
var descId = this.id.replace("thumb", "desc");
var description = $('.game-descriptions').children('#' + descId);
// or simply $("#" + descId);
description.toggle("slow");
});
});
HTML
<div>
<div class="thumbnail" id="thumb-1">Thumb 1</div>
<div class="thumbnail" id="thumb-2">Thumb 2</div>
<div class="thumbnail" id="thumb-3">Thumb 3</div>
</div>
<div class="game-descriptions">
<div class="description" id="desc-1">Description One</div>
<div class="description" id="desc-2">Description Two</div>
<div class="description" id="desc-3">Description Three</div>
</div>
Your technique for targeting the correct 'description' will depend on your actual DOM structure, however.
Also note that I substituted the toggle method for your if statement, as the logic you have is equivalent to what it does (i.e. toggling object visibility).

How to get class of item selected in jquery?

I have 2 images (.field-img) , wrapped in a container (.group-container),
each of the images are in a unique field id, so my tpl is broken down into
<div class=group-container>
<div id=field1>
<div class=field-img>
</div></div>
<div id=field2>
<div class=field-img>
</div></div>
</div>
my js is
$(".group-container .field-img").click(function() {
alert(".group-container .field-img");
what I would like is to detect automatically if the image belongs to field1 or field2.
So I could alert (".group-container .field1/2 .field-img");
How would I do this?
Thanks for any help
$(".group-container .field-img").click(function() {
var field=$(this).parent().attr('id');
});
An alternative to Izzey's solution is to use .closest with an attribute starts with selector (or classname because it would be more appropriate for those divs to have a common class)
$(".group-container .field-img").click(function() {
var field = $(this).closest("[id^=field]")[0].id;
});
or, with a common classname,
html
<div class=group-container>
<div class="field" id=field1>
<div class=field-img>
</div></div>
<div class="field" id=field2>
<div class=field-img>
</div></div>
</div>
js
$(".group-container .field-img").click(function() {
var field = $(this).closest(".field")[0].id;
});
$(".group-container .field-img").click(function() {
var field = this.parentNode.id;
alert (".group-container ." + field + " .field-img");
});
$(".group-container .field-img").each(function() {
$(this).click(function(){
var fieldid=$(this).parent().attr('id');
});
});
Since one element is inside the other, the click will propagate up anyway, so you could always just bind the click to the parent element and do :
$('div[id^="field"]').on('click', function() {
alert(".group-container "+this.id+" .field-img");
});
FIDDLE
or even get them all dynamically:
$('div[id^="field"]').on('click', function(e) {
alert('.'+this.parentNode.className+" "+this.id+" ."+e.target.className);
});
FIDDLE
​

How do I use a function argument for this jquery code, or is there a better solution?

I have about 50 p tags and next to these are again 50 divs. on click of each p tag, its div should be shown and the rest hidden. How do i acheive this. I can use something like below:
$(function() {
$('.p1').click(function(){
$('.div1').show();
$('.div2','.div3','.div4','.div5','.div6',.........,'.div50').hide()
})
$('.p2').click(function(){
$('.div2').show();
$('.div1','.div3','.div4','.div5','.div6',.........,'.div50').hide()
})
//////////////
//////
})
but as you see that this is not an effiecient solution. I am also not sure how the jquery each can be leveraged here or how can this implementation be done using arrays. Can somebody point me in the right direction. I think we should use a function and pass that no. as a parameter, but I dont know how to use custom functions in jquery.
UPDATE:
This is what I have done
$(function() {
$('.p1').click(function() {
$('.div').hide();
$('.d1').show();
})
})
I have added the class div to all of my 50 divs and I am showing d1 on click of p1. Now how do I replace 1 for each instance till 50.
I would have a common class to all div and p so that the binding the handler and the hide can be simple. And for the div, I would associate a data-tag to each p to link each p tag to div
<p class="p1 pclass" data-showdiv="div1">
...
</p>
<p class="p2 pclass" data-showdiv="div2">
..
<div class="mydiv div1" ..>
..
</div>
<div class="mydiv div2" ..>
..
</div>
And the script would be,
$(function() {
$('.pclass').click(function(){
$('.mydiv').hide();
$('.' + $(this).data('showdiv')).show();
});
});
As Jason told,
Use this
$('p').click(function() {
$('div').hide();
$(this).next('div').show();
});
If the div is next to each paragraph.
But, if there's an element between p and div, it wont work.
For you problem, you can do,
$('p').click(function() {
$('div').hide();
var divClass = $(this).attr("class").replace('p','div');
$('.' + divClass).show();
});
provided you have only p1, p2 .... in paragrah classes ;)
Update
See this fiddle
Notice , we have <br> tags between <p> and <div> as you wanted.
Assuming your HTML structure is
<p>Some text</p>
<div>More text to hide and show</div>
<p>Some text</p>
<div>More text to hide and show</div>
<p>Some text</p>
<div>More text to hide and show</div>
....
Use the following in your $(function(){}); method:
$('p').click(function() {
$('div').hide();
$(this).next('div').show();
});
var dvs = ['.div1','.div2','.div3','.div4','.div5','.div6',.........,'.div50'];
$('p').click(function() {
var index = parseInt(this.className.replace('p','')) - 1;
$(dvs[index]).show();
$(dvs.join(', ')).not(dvs[index]).hide();
});
The jQuery click event will automatically be registered on all elements that match the selector, so you shouldn't have to use the each() method. I would suggest having two CSS classes to distinguish between elements that have this toggling behaviour and elements that are primary (i.e. should be shown when their parent is clicked).
The markup:
<body>
<p class="togglable">
<div class="primary">
This is the primary div that will be shown when our parent is clicked.
</div>
<div>Regular div child</div>
<p>Nested paragraph</p>
<ul>
<li>A list perhaps</li>
</ul>
</p>
<p class="togglable">
<div class="primary">
This is the primary div that will be shown when our parent is clicked.
</div>
<div>Regular div child</div>
<p>Nested paragraph</p>
<ul>
<li>A list perhaps</li>
</ul>
</p>
<p>This is a normal paragraph</p>
</body>
The code:
$(function () {
$('.togglable').click(function () {
// hide all our children
$(this).children().hide();
// now only show our primary chlid
// NOTE: we pass 'this' as the second argument
// so that the selector will only apply to the
// children of the element that was clicked
// (i.e. we are providing a custom context for the selector).
$('.primary', this).show();
// You could even use the position of the child as well:
// $(this).children().first().show();
// This will show the first child element.
});
});
In this example all elements with the class togglable will show their primary child element when clicked and hide all other child elements.

Categories