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

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).

Related

Targeting Multiple Elements with One Function

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>

Find sibling with Javascript and Hammer.js

I have made a simple system which detects double taps. I want to show a heart icon when someone double taps on an image, just like on Instagram.
This is what my code looks right now:
var elements = document.getElementsByClassName('snap_img');
[].slice.call(elements).forEach(function(element) {
var hammertime = new Hammer(element),
img_src = element.getAttribute('src');
hammertime.on('doubletap', function(event) {
alert(img_src); // this is to test if doubletap works
// Some javascript to show the heart icon
});
});
This is what the HTML looks like:
<div class="snap_item">
<div class="snap_item_following_info">
<img class="snap_item_following_img" src="res/stat/img/user/profile/small/1.fw.png" alt="#JohnDoe" />
<a class="snap_item_following_name" href="#">#JohnDoe</a>
<div class="snap_too">
</div>
</div>
<img class="snap_img" src="res/stat/img/user/snap/43/2.fw.png" alt="#ErolSimsir" />
<div class="like_heart"></div>
<div class="snap_info">
<div class="snap_text">
LA is the shit...
<a class="snap_text_hashtah" href="#">#LA_city_trip</a>
</div>
<div class="snap_sub_info">
<span class="snap_time">56 minutes ago</span>
<div class="like inactive_like">
<div class="like_icon"></div>
<div class="like_no_active">5477</div>
</div>
</div>
</div>
</div>
So when the element 'snap_img' is double tapped, I need to get the element 'like_heart' which is one line below the snap_img element. How do I get that sibling element and fade it in with JQuery?
Like this
[].slice.call(elements).forEach(function(element) {
var hammertime = new Hammer(element),
img_src = element.getAttribute('src');
hammertime.on('doubletap', function(event) {
alert(img_src); // this is to test if doubletap works
$(element).next().text('♥').hide().fadeIn();
});
});
P.S. I've added that heart text, since the sibling was empty.
On the event handler, i would do $(element).parent().find('.like_heart').fadeIn(); So the code is not dependant on the element ordering.
(To clarify to selector: take the parent element which is the div.snap_item and find an element with class like-heart inside it)

If href equals id of another div do function

I have a hidden div with the details of a thumbnail that is visible on the page. When you click on the thumbnail, it should fadein or slideup the div with details.
I have set with jquery incremented ID's to each ".portfolio-item-details" to identify each one and then have set with jquery the same ID's to the href of the thumbnail.
<section id="portfolio1" class="portfolio-item-details hidden">content</section>
<a class="open-portfolio-item-details" href="#portfolio1" title="">
<img src="thumbnail.jpg">
</a>
<section id="portfolio2" class="portfolio-item-details hidden">content</section>
<a class="open-portfolio-item-details" href="#portfolio2" title="">
<img src="thumbnail.jpg">
</a>
Since this is done dynamically, how can I with jquery fadeIn or slideUp the ".portfolio-item-details" if the href is equal to the ID. Basically thumbnail with "#portfolio1" should slide up the div with "#portfolio1" on click.
This is my jquery code which to add the IDs and HREF is working perfectly but not working to slideUp or fadeIn the div with the same ID.
$(document).ready(function () {
var i=0;
$(".portfolio-item-details").each(function(){
i++;
var newID="portfolio"+i;
$(this).attr("id",newID);
$(this).val(i);
});
var i=0;
$(".open-portfolio-item-details").each(function(){
i++;
var newReadMoreHREF="#portfolio"+i;
$(this).attr("href",newReadMoreHREF);
$(this).val(i);
if ($(".portfolio-item-details").attr("id") == "newReadMoreHREF") {
$(this).fadeIn();
}
});
});
SOLUTION
Thanks to Austin's code, I was able to modify it to work with mine.
Check here: http://jsfiddle.net/jdoimeadios23/xpsrLyLz/
You want something like this?
HTML
<div class="image" value="1">
<img src="thumbnail.jpg" />
</div>
<div id="portfolio1" class="details">details</div>
<div class="image" value="2">
<img src="thumbnail.jpg" />
</div>
<div id="portfolio2" class="details">more details</div>
JS
$(document).ready(function () {
$('.details').fadeOut(1);
$(".image").click(function () {
var num = $(this).attr("value");
$("#portfolio"+num).fadeIn(1000);
});
});
JSFiddle Demo
You don't even need to bother with ID's so long as the next div below each image is it's details.
The problem is in this block
if ($(".portfolio-item-details").attr("id") == "newReadMoreHREF") {
$(this).fadeIn();
}
Because you're having two errors, the first one is that newReadMoreHREF is a variable, not a string in your HTML or a value to any variable and so on.
Second thing is, that in the variable declaration you're using "#portfolio"+i;, which would be good if you were about to select an element. But using it in the jQuery iif statement with .attr('id') will again cause a havoc.
The thing that you need is something like this
$(".open-portfolio-item-details").each(function(){
i++;
var newReadMoreHREF="portfolio"+i; // removed #
$(this).attr("href",newReadMoreHREF);
$(this).val(i);
if ($(".portfolio-item-details a").attr("id") == newReadMoreHREF) {
// you need to access the hyperlink in the element, not
// the element itself. this portfolio1 ID is of a hyperlink
// again here, this is referencing the main iterator.
$(this).fadeIn();
// are you sure you want to fade the .open-portfolio-item-details?
}
});
Removed the hash sign and then called the variable value to check against. It would execute to be true if the condition is true.
Try this:
HTML:
content
<section id="portfolio2" class="portfolio-item-details hidden">content</section>
<a class="open-portfolio-item-details" href="#portfolio2" title="">
<img src="thumbnail.jpg">
</a>
<div id="portfolio1" class="portfolio" hidden>Portfolio 1</div>
<div id="portfolio2" class="portfolio" hidden>Portfolio 2</div>
Jquery:
$('a.open-portfolio-item-details').on('click', function (e) {
e.preventDefault();
var id = $(this).attr('href');
$('.portfolio').hide();
$('.portfolio' + id).fadeIn();
});
Couldn't get the fiddle link for some reason.
Edit:
I don't know the name of the class that shows the content you want displayed, so as an example I'm using portfolio. Try putting this code into a fiddle

jQuery - Add class to parent container based on content of child container

I would like to add a class to the outer (parent) container based on the content of a child container. I am able to add a class to the child container based on its content, but If I try to add the class to the parent container, it does it to all of the containers on the page instead of just the current container. Could someone help me update my code so that it only adds the class to the parent container and not all containers that share the same class? Thanks.
jQuery:
$('div.promotion-type').each(function () {
var promotion = $(this).html();
console.log(promotion);
if (promotion === "Special Event") {
$("div.calendar-event").addClass("special-event"); // this is the only one with a class created for it so far
} else if (promotion === "Daily Promotion") {
$("div.calendar-event").addClass("daily-promotion");
}
});
HTML: (1 of many containers)
<li class="hidden-xs col-sm-6 col-md-4">
<div class="calendar-event">
<div class="event-details-container">
<div class=" col-xs-4 calendar-thumbnail">
<a href="/warroad-calendar/canadian-day">
<img src="/_images/warroad/calendar/may-june-2014/canadianDay.jpg" border="0" alt="" />
</a>
</div>
<h3>Canadian Day</h3>
<h4>8 a.m. - 6 p.m.</h4>
<strong></strong><br />
<div class="hidden-xs hidden-sm hidden-md hidden-lg promotion-type">Daily Promotion</div>
</div>
</div>
</li>
Change this:
$("div.calendar-event").addClass("special-event");
to this:
$(this).parents("div.calendar-event").addClass("special-event");
As it appears you already know, using the selector $("div.calendar-event") is going to select all <div> elements with the class calendar-event.
By using $(this).parents("div.calendar-event"), you're going to look through all parents of the starting <li> element, starting with the closest parent and progressing outwards. When it finds the parent that is a <div> element with the class calendar-event, it's going to call .addClass() on that parent element.
The problem is that you are doing a new selection instead of using the current element. Try...
$(this).parent().parent().addClass(...);
...or possibly...
$(this).parents('div.calendar-event').addClass(...);
...instead.
Instead of this-
$("div.calendar-event", this).addClass("special-event");
try this:
this.find("div.calendar-event").addClass("special-event");
Use text() instead of html()
remove the classes first
use $(this)
Code:
$('div.promotion-type').each(function () {
var promotion = $(this).text();
console.log(promotion);
$(this).parent().removeClass("special-event");
$(this).parent().removeClass("daily-promotion");
$(this).parent().addClass(
promotion === "Special Event" ? 'special-event': 'daily-promotion');
});

Show certain DIVs with onclick

In a Blog you can determine a tag for each post e.g. Video, Photo, Quote etc... If I created a div class for each tag e.g.
<div class="Video"></div>
<div class="Photo"></div>
<div class="Quote"></div>
How can I create a onclick link so when I click it only shows div's called Video and hides all other div's?
DEMO HERE
Using Jquery....
$(document).ready(function()
{
$('.filter').click(function(e)
{
e.preventDefault();
var filter = $(this).html();
$('.boxes').hide();
$('.'+filter).show();
});
});
Then in your HTML
<a class="filter">Video</a>
<a class="filter">Photo</a>
And your divs....
<div class="boxes Video">Blahblah</div>
<div class="boxes Photo">Blahblah</div>
Or you can do it using data attributes, to keep your HTML more readable...but this works too
DEMO HERE
I'd recommend using jQuery for this. And it would be much better if you give all your "tag" divs a class like, for example, tag and separated with a space it's specific type.
For example class="tag audio". But this should work for now:
$('div').click(function () {
var tags = ['Video', 'Photo', 'Quote'], tag = $(this).attr('class');
if ($.inArray(tag, tags)) {
$('.' + tag).show();
$('div').not('.' + tag).hide();
}
});

Categories