How to take element from collection by specific class name using jQuery? - javascript

I have to make a slider control using jQuery. In each slide you can have a content like images, paragraphs and so on.
<div class="slide first current">
<h1>Ninja Superman slide</h1>
<p>Here's some text.</p>
<img src="http://blogs.telerik.com/images/default-source/miroslav-miroslav/super_ninja.png?sfvrsn=2" width="300" height="300">
</div>
<div class="slide">
<h1> Ninja Samurai</h1>
<p>Here's some text about ninja samurais</p>
<img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRVNH4RuAsomFkrv9tWiz_VBaCbVSWbC7gDXtOag9e7K_JHuC6zZR5Es-Y" width="500" height="300">
</div>
<div class="slide last">
<h1>The birth of a ninja</h1>
<p>Some text about the birth of a ninja from egg.</p>
<img src="http://forums.academy.telerik.com/?qa=blob&qa_blobid=5564423925526764256" width="300" height="300">
</div>
I have 2 buttons for previous and next slide.
<input type="button" id="prev-btn" value="Previous slide" />
<input type="button" id="next-btn" value="Next slide" />
On each div (slide content) I have a class "slide", so I can locate is as a slide. I'm made a collection by taking all the elements from document with class "slide".
var $slides = document.getElementsByClassName("slide");
Now I have to make a function onNextButtonClick(), that will change my slides. But I don't know how to take the current slide. I have a class "current", given on first element by default. So my question is: how to take an element from collection with specific attribute. Something like that:
var $currentSlide = $slides[element.class == "current"];

Since you use jQuery, I think you better should use jQuery selector to select element.
You can select element with several class by:
var $slides = $(".slide.current");
You can find out infomation about how to choose element according to class, attribute or state here
enter link description here

If the elements with the class current are child nodes of $slides, the following code will select them all:
$('.current', $slides)
The second parameter to the call of the $ function is the scope for the selector.
If you want to get the first element of all the matched elements, you can do this as follows:
$('.current', $slides)[0]
You can see a demonstration here.

To select the current slide you can use
$(".current")
also, you can try out jQuery orbit if you want a simple way to make a slider
http://zurb.com/playground/orbit-jquery-image-slider

Best to use the jQuery/sizzle selectors.
var $slides = document.getElementsByClassName("slide");
becomes
var $slides = $(".slide");
var $currentSlide = $slides.filter(".current");

You can add class to the buttons to get the click event
<input class="next-prev-btn" type="button" id="prev-btn" value="Previous slide" />
<input class="next-prev-btn" type="button" id="next-btn" value="Next slide" />
After that get the click event
$(".next-prev-btn").on('click',function(){
// get the clicked button's id
var clickedButton = $(this).attr('id');
$('.slide').each(function() {
if($(this).hasClass('current'))
{
// here you will get the div which have current class
// your business logic
// you can get your clicked button also by
if(clickedButton=='prev-btn')
{
// your logic for previous button click
}
else
{
// your logic for next button click
}
// if you are done with your functionality you can break the look here to prevent unwanted execution through the loop
break;
}
});
});

Perhaps you should use a toggle(); ?
Use jQuery! Add to head:
http://www.w3schools.com/jquery/jquery_install.asp
Working on jQuery is more easy and faster.

Related

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)

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

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');
});

how to hide/remove all text in-between two elements?

lets say i have this lump of HTML:
<div class="container">
<span class="title">Heading 1</span>
This is a description..<br />
This is the second line..
<div class="image"><img src="image.jpg" /></div>
</div>
What i want to do using jQuery/JavaScript is hide/remove all text and elements between <span class="title"> and <div class="image">.
I've looked all over and found pretty much nothing. Any ideas on how i could do this?
How about something like this? http://jsfiddle.net/ZW8q2/1
var foo = $('.container').children(':not(br)');
$('.container').html('').html(foo);
You could try:
var str = $('.container .title').text() + $('.container .image').html();
$('.container').html(str);
JS Fiddle.
Try this:
Place a tag around what you want to hide, give div an ID name. So in the end your will look like:
<div id = "hideMe" style ="display:block">...Your Content...</div>
Use this javascript:
function hide()
{
document.getElementById('hideMe').style.display = "none";
return;
}
Have the Javascript function called whenever you want to hide the stuff between the div from a button (or other control) like this:
<input type= "submit" onclick ="hide()">

Categories