Bind jQuery to multiple instances of a div - javascript

I am currently using the "SwipeJS" plugin (https://github.com/bradbirdsall/Swipe) to create a photo slider.
Following is the code for the div. I have MULTIPLE instances of this div on a single page (below am using 2 div's only.
<div id='slider1' class='swipe'>
<div class='swipe-wrap'>
<div class="swipe_index"><img src="/images/default/business.jpg" alt="/images/default/business.jpg" id="img1_1" width="100" height ="100" / > </div>
<div class="swipe_index"><img src="/images/default/News.jpg" alt="/images/default/News.jpg" id="img1_2" width="100" height ="100" / > </div>
<div class="swipe_index"><img src="/images/default/Gaming.jpg" alt="/images/default/Gaming.jpg" id="img1_3" width="100" height ="100" / > </div>
</div>
</div>
<span class="nav prev">Prev</span>
<span class="nav next">Next</span>
<span class="nav now">now</span>
<div id='slider2' class='swipe'>
<div class='swipe-wrap'>
<div class="swipe_index"><img src="/images/default/business.jpg" alt="/images/default/business.jpg" id="img1_1" width="100" height ="100" / > </div>
<div class="swipe_index"><img src="/images/default/News.jpg" alt="/images/default/News.jpg" id="img1_2" width="100" height ="100" / > </div>
<div class="swipe_index"><img src="/images/default/Gaming.jpg" alt="/images/default/Gaming.jpg" id="img1_3" width="100" height ="100" / > </div>
</div>
</div>
<span class="nav prev">Prev</span>
<span class="nav next">Next</span>
<span class="nav now">now</span>
I am not aware as to how to bind the following jquery code to every instance of the div. Below is my attempt to modify the jquery
<script>
$(document).ready(function() {
$('.swipe').each(function(){
Slider = $(this).Swipe({
continuous: false,
stopPropagation: true,
callback: function(index, elem) {
alert(index);
},
}).data('Swipe');
$('.next').click(function(data){
Slider.next();
//alert($(".swipe_index .current").data('index'));
});
$('.prev').on('click', Slider.prev);
});
});
</script>
However, the above code doesn't work well. This only binds the jquery to the last div.Can someone please help correct the code above?
Whats the best way to bind jquery to multiple instances of divs on a webpage.

Try
$(document).ready(function () {
$('.swipe').each(function () {
//create a closure variable instead of a global one
var Slider = $(this).Swipe({
continuous: false,
stopPropagation: true,
callback: function (index, elem) {
alert(index);
},
}).data('Swipe');
//use relative tranversal to find the next/prev elements
$(this).next().next('.next').click(function (data) {
Slider.next();
//alert($(".swipe_index .current").data('index'));
});
//try using $.proxy
$(this).next('.prev').on('click', $.proxy(Slider.prev, Slider));
});
});

Related

Mouseover function not working for first time

With this function i want to replace a static image with an animated image (gif) on mouseover. But it's not working only on FIRST mouseover. Is there someone that could help me?
JQuery function:
function mouseListener(imageDiv, image, animated, static)
{
$(function() {
$(imageDiv).hover(
function() {
$(image).attr("src", animated);
},
function() {
$(image).attr("src", static);
}
);
});
}
HTML:
<div onmouseover="mouseListener('#would_youDiv','#would_you','images/would_you.gif','images/would_you.jpg');" id="would_youDiv" class="container">
<a href="work.html">
<img id="would_you" class="img-fluid" src="images/would_you.jpg" width="100%" height="100%" />
<div class="overlay">
<div class="text">WOULD YOU</div>
</div>
</a>
</div>
You could make this much easier by generalizing the logic with classes and data elements.
$(document).ready(function() {
$('.hover-image-container').hover(
function() {
//find the image in the container
var $img = $(this).find('img');
//set the src to the animaged src on it
$img.attr('src', $img.data('animated-src'));
},
function() {
//find the image in the container
var $img = $(this).find('img');
//set the src to the original src
$img.attr('src', $img.data('src'));
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container hover-image-container">
<a href="work.html">
<img src="images/would_you.jpg" data-src="images/would_you.jpg" data-animated-src="images/would_you.gif" width="100%" height="100%" />
<div class="overlay">
<div class="text">WOULD YOU</div>
</div>
</a>
</div>
Your mouseListener method is called when the mouseover event occurs, which is when it creates the listener to the event, instead of acting on the event. You don't need to add the listener, since you've already registered the function to be called on mouse over, you just need to do the action you want for that event.
You need to either put that binding somewhere else, or create two methods that are bound to onmouseover and onmouseout.
For example, if you want to go the two methods route (as that's most similar to your current code):
<div onmouseover="mouseOverListener('#would_youDiv','#would_you','images/would_you.gif','images/would_you.jpg');" onmouseout="mouseOutListener('#would_youDiv','#would_you','images/would_you.gif','images/would_you.jpg');" id="would_youDiv" class="container">
<a href="work.html">
<img id="would_you" class="img-fluid" src="images/would_you.jpg" width="100%" height="100%" />
<div class="overlay">
<div class="text">WOULD YOU</div>
</div>
</a>
</div>
And then in your Javascript:
function mouseOverListener(imageDiv, image, animated, static) {
$(image).attr("src", animated);
}
function mouseOutListener(imageDiv, image, animated, static) {
$(image).attr("src", static);
}
You don't need a js function
HTML
<div class="container">
<a href="work.html">
<img class="img-fluid" src="images/would_you.jpg" width="100%" height="100%" onmouseover="this.src='images/would_you.gif'" onmouseout="this.src='images/would_you.jpg'"/>
<div class="overlay">
<div class="text">WOULD YOU</div>
</div>
</a>
</div>

Getting id of collapsible div in Jquery and Bootstrap

I have multiple(it can be 100+) collapsible div (using bootstrap)
<div>
<a href="#id1" data-toggle="collapse">
<div class="col-lg-12">Title</div>
<div class="image">Image</div>
</a>
<div id="id1" class="collapse">
<div class="col-lg-12">Description</div>
</div>
</div>
<div>
<a href="#id2" data-toggle="collapse">
<div class="col-lg-12">Title</div>
<div class="image">Image</div>
</a>
<div id="id2" class="collapse">
<div class="col-lg-12">Description</div>
</div>
</div>
And have Jquery
$('#id1').on('show.bs.collapse', function () {
$(".image").addClass('hidden');
});
$('#id1').on('hidden.bs.collapse', function () {
$(".image").removeClass('hidden');
});
I want to add hidden class on show.bs.collapse(this is from bootstrap) and remove hidden class on hidden.bs.collapse'With the jq code above I can do this just with one div that has id1. But how can I do this independently?
Try not to subscribe on the elements by ids but by element type
$('a').on('show.bs.collapse', function () {
$(this).next().find("div.image")[0].addClass('hidden');
});
$('a').on('hidden.bs.collapse', function () {
$(this).next().find("div.image")[0].removeClass('hidden');
});
Where
$(this)
should return a pointer to the collapsed/uncollapsed element
next()
should move pointer to the next element ( div id="id1" as example)
find("div.image")[0]
will find div with class "image" and take the first found element
then you can hide the image in this block or show it without using ids
If you're using
$(".image").addClass('hidden');
this will hide all the images in all blocks (not only in that one that has been collapsed)
Id refers to one element on the DOM therefore you should use classes instead. Therefore you should select divs based on their classes.
The following is a possible solution:
<div>
<a href="#id1" data-toggle="collapse">
<div class="col-lg-12">Title</div>
</a>
<div class="some-class collapse ad-col-2">
<div class="col-lg-12">Description</div>
<div class="image"></div>
</div>
</div>
<div>
<a href="#id2" data-toggle="collapse">
<div class="col-lg-12">Title</div>
</a>
<div class="some-class collapse ad-col-2">
<div class="col-lg-12">Description</div>
<div class="image"></div>
</div>
</div>
Jquery:
$('.some-class').on('show.bs.collapse', function () {
$(".image").addClass('hidden');
});
$('.some-class').on('hidden.bs.collapse', function () {
$(".image").removeClass('hidden');
});

Jquery Dropdown List not sliding up after mouse leave

So I was basically trying to create a drop-down list with jquery. I was successful in achieving but came across with a slight problem. Here's the code
HTML
<div class="dropdown_heading">
text
</div>
<div class="dropdown_container">
<div class="">
Competition1
</div>
<div class="">
Competition2
</div>
<div class="">
Competition3
</div>
</div>
JQUERY
$(document).ready(function(){
$(".dropdown_heading").mouseenter(function(){
$(".dropdown_container").slideDown();
});
$(".dropdown_container").mouseleave(function(){
$(".dropdown_container").slideUp();
});
});
Once I hover over the dropdown_heading the dropdown shows-up and I'm able to navigate over it but the only way the it slides back up is if i actually have the cursor in the dropdown_container. If I try to slide it up removing the mouse from dropdown_heading, the dropdown is still visible. How would I be able to slide the submenu back up when the mouse leaves both div_container and div_heading?
I've tried to execute this function but therefore I am unable to navigate over the container. Thanks.
$(".dropdown_heading").mouseleave(function(){
$(".dropdown_container").slideUp();
});
You can try a timer based solution like
jQuery(function($) {
var $target = $(".dropdown_container");
$('.dropdown_heading').hover(function() {
clearTimeout($target.data('hoverTimer'));
$target.stop(true, true).slideDown(500);
}, function() {
var timer = setTimeout(function() {
$target.stop(true, true).slideUp();
}, 200);
$target.data('hoverTimer', timer);
});
$target.hover(function() {
clearTimeout($(this).data('hoverTimer'));
}, function() {
$(this).stop(true, true).slideUp();
});
});
.dropdown_container {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown_heading">
text
</div>
<div class="dropdown_container">
<div class="">
Competition1
</div>
<div class="">
Competition2
</div>
<div class="">
Competition3
</div>
</div>
The toggleClass() method toggles between adding and removing one or more class names from the selected elements.
This method checks each element for the specified class names. The class names are added if missing, and removed if already set - This creates a toggle effect..
Try this,
$(document).ready(function(){
$(".dropdown_heading").mouseenter(function(){
$(".dropdown_container").toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown_heading">
text
</div>
<div class="dropdown_container">
<div class="">
Competition1
</div>
<div class="">
Competition2
</div>
<div class="">
Competition3
</div>
</div>

How can I use jQuery to highlight ONLY the selected thumbnail?

Here is a screenshot of what I'm trying to accomplish:
Here's a snippet of the html:
<section id="obstacles">
<div class="row">
<div class="large-3 columns">
<a href="#">
<div class="box inactive topBox" id="theTank">
<img src="http://fpoimg.com/150x150">
</div>
</a>
</div>
<div class="large-3 columns end">
<a href="#">
<div class="box inactive topBox rightBox" id="sundaeSlide">
<img src="http://fpoimg.com/150x150">
</div>
</a>
</div>
</div>
<div class="row">
<div class="large-3 columns">
<a href="#">
<div class="box inactive" id="hamster">
<img src="http://fpoimg.com/150x150">
</div>
</a>
</div>
<div class="large-3 columns end">
<a href="#">
<div class="box inactive rightBox" id="downTheHatch">
<img src="http://fpoimg.com/150x150">
</div>
</a>
</div>
</div>
<div class="row">
<div class="large-6 columns large-offset-6">
<img id="smallSlime" src="/assets/otherAssets/smallSlime.png">
</div>
</div>
<div class="row">
<div class="large-6 columns large-offset-6">
<a href="#">
<hgroup>
<h2>Down the Hatch</h2>
<h3>6ft Slide Covered in Gunk!</h3>
</hgroup>
</a>
</div>
</div>
</section>
And here's the jQuery I'm using to change the large picture that shows up on the right:
$(document).ready(function() {
$("#theTank").click(function(event){
event.preventDefault();
$('.largeObstacles').html("<img src='/assets/obstacles/the-tank.png' />");
$(this).toggleClass('active inactive');
})
$("#sundaeSlide").click(function(event){
event.preventDefault();
$('.largeObstacles').html("<img src='/assets/obstacles/sundae-slide.png' />");
$(this).toggleClass('active inactive');
})
$("#hamster").click(function(event){
event.preventDefault();
$('.largeObstacles').html("<img src='/assets/obstacles/hamster-wheel.png' />");
$(this).toggleClass('active inactive');
})
$("#downTheHatch").click(function(event){
event.preventDefault();
$('.largeObstacles').html("<img src='/assets/obstacles/down-the-hatch.png' />");
$(this).toggleClass('active inactive');
})
$("#pickIt").click(function(event){
event.preventDefault();
$('.largeObstacles').html("<img src='/assets/obstacles/pick-it.png' />");
$(this).toggleClass('active inactive');
})
$("#theWringer").click(function(event){
event.preventDefault();
$('.largeObstacles').html("<img src='/assets/obstacles/the-wringer.png' />");
$(this).toggleClass('active inactive');
})
})
Right now, when I click on the thumbnail image on the left, the background turns yellow and the correct large image displays on the right. However, when I click another image, the highlighted image remains highlighted. I am sure there is an easy fix to this, I'm just not confident of how to traverse the DOM to do what I want. Any help is greatly appreciated!
How about:
$(".active").toggleClass("active inactive");
Add this as the first line in your click functions.
$("#theTank, #anotherimg").click(function(event){
event.preventDefault();
var imgsrc = $(this).find('img').attr('src');
$('.largeObstacles').html("<img src='"+imgsrc+"' />");
$(this).toggleClass('active inactive');
});
Try this:
(function() {
var LMenuItems = $("a > .box");
var RMenuItem = $(".largeObstacles");
LMenuItems.foreach(function(MenuItem) {
MenuItem.onclick = function(event) {
event.preventDefault();
RMenuItem.html(MenuItem.childNodes[1]);
// Combined with Bill Read's answer -> Box class containing active class
$(".box > .active").toggleClass("active inactive");
}
});
}());
This method allows you to select all the menu items you have on the left menu by creating an array. Using .foreach allows you to iterate through the array and bind the click event to each menu object you have.
As others have mention. Your code makes it difficult because you are using individual event listeners for each element.
A good way to solve this would be to make your code more universal.
Adjusting for my lack of attention in seeing that the image source are different for small/large images.
First make you dom elements share a universal selector (.small-image)
And use a data-attribute on you element containing the large image src.
Note I used the same image for both just to make examples easier. Each data-imgsrc should have its respective image.
<div class="row">
<div class="large-3 columns">
<a href="#">
<div class="box inactive small-image" id="hamster" data-imgsrc="/assets/obstacles/the-tank.png">
<img src="http://fpoimg.com/150x150">
</div>
</a>
</div>
<div class="large-3 columns end">
<a href="#">
<div class="box inactive rightBox small-image" id="downTheHatch" data-imgsrc="/assets/obstacles/the-tank.png">
<img src="http://fpoimg.com/150x150">
</div>
</a>
</div>
</div>
Then with your javascript we can simple pull the data-imgsrc attribute from out clicked element and set it to the large container.
$('.small-image').on('click', function (ev) {
ev.preventDefault();
// remove any currently active small-images
$('.small-image.active').removeClass('active');
// make clicked active
$(this).addClass('active');
// Get the image src from the clicked elements data-imgsrc attribute
// and inject into large container
var imgText = '<img src="{img-src}" />';
var imgSrc = $(this).data('imgsrc');
$('.largeObstacles').html(imgText.replace('{img-src}', imgSrc);
});
This seems to be the best solution I've found:
("#obstacles .small-image").on('click', function(){
event.preventDefault();
var selector = '#'+$(this).attr('id');
var image = $(this).find('img').attr('data-attr-putItOver');
$(".small-image.active").removeClass('active').addClass('inactive');
$(selector).addClass('active');
$('.largeObstacles').html("<img src='"+image+"' />");
});

Animate opacity change on hover not working

I want to show a div when a user hovers the element. I want that when you hover over div named distinguished the div class prod-desc changes it's opacity to 1.
Please help me and thank you in advantage!
Here's the HTML:
<section id="distinguished" class="four columns"> <a class="dist-img" href="#" alt="" border="0" > <img src="images/e1.png" onClick="window.location='#Url.Action("Details", "Item", new { id = section["Id"], storeid = section["PortalId"], name = section["ProductTitle"] })'"/> </a>
<div class="descContent">
<div class="distinguished-bar"> <a class="categoryMain" href="#Url.Action("Details", "Item", new { id = section["Id"], storeid = section["PortalId"], name = section["ProductTitle"] })'"></a> <a class="btAdd" href="#" title="ADD"><span class="iconAdd"></span>
<p>ADD</p>
</a> </div>
<div class="infoContent">
<div class="prod-desc ">
<p>Category</p>
<p>Title</p>
<p>Description</p>
</div>
<div class="prod-price">
<div>
<p class="priceTitle">Precio</p>
<span class="priceRegular">$300</span></div>
</div>
<div class="buttonsBox"> <a class="btAddLarge hom2" id="addToCart" href="/Cart/AddToCart">
<p>#this.Message("Add")</p>
</a> </div>
</div>
</div>
</section>
Here's the jQuery:
$('.prod-desc').hover(function () {
$('.prod-desc', this).stop().animate({
"opacity": 1
});
}, function () {
$('.prod-desc', this).stop().animate({
"opacity": 0
});
});
Try using mouseover and mouseleave instead:
$('.prod_desc').mouseover(function() {
$(this).stop().clearQueue().animate({
"opacity": 1
});
$('.prod_desc').mouseleave(function() {
$(this).stop().clearQueue().animate({
"opacity": 0
});
});
});​
You can see it in action in this fiddle: http://jsfiddle.net/svNpQ/3/
It's easy, just use in your code:
$('#distinguished').hover(function() {
$('.prod-desc').animate({"opacity": 1});
});
Here is the example: jsFiddle Demo
In your case you must refer to the element by id, which is 'distinguished'. Then you define the action which is hover and inside of the function you specify which element and what to do, in your case '.prod-desc' animate (change css property) to 1.
Remember to set initial css opacity property of .prod-desc to something lower than 1 to see the difference.
Target the element you wish to attach the event handler to, not the element that will have the fading effect :
$('#distinguished').hover(function() {
$('.prod-desc', this).stop().animate({"opacity": 1});
},function() {
$('.prod-desc', this).stop().animate({"opacity": 0});
});​
FIDDLE

Categories

Resources