Change background JQuery depending on img src - javascript

So I am trying to change the background color of a div after the page loads.
The div with the background and the img are inside an li.
When the mouse enters the .dlmain div I check the img src and give the div .darkbg a background depending on the img src
THE ISSUE: It shows me the correct img src the first time and second time but then on the next div I enter it shows the previous divs img src. I have about 100 divs that the mouse enters and background color should be changed
Am I supposed to have a .each function here? I tried this with no luck
$(document).ready(function () {
$(document).on("mouseenter", ".dlmain", function () {
if ($('.carimg').attr('src') == '/css/1359532013.jpg') {
$(".darkbg").css({
"backgroundColor": "#EE1C25"
});
alert($('.carimg').attr('src'));
} else if ($('.carimg').attr('src') == '/css/1359532047.jpg') {
$(".darkbg").css({
"backgroundColor": "blue"
});
alert($('.carimg').attr('src'));
} else {
alert($('.carimg').attr('src'));
}
});
});
Here is the HTML:
<li id="13592635281366253285" class="myli" style="width:170px;height:170px;">
<div class="favs"></div>
<div class="mylimg" style="background:url(/images/th135926352813662532851.jpg) 50% 50% no- repeat;"></div>
<div class="darkbg" style="background-color: rgb(238, 28, 37); opacity: 0;"></div>
<div class="dlprice">$69.99</div>
<div class="dlmain" style="top: 153px;">
<img class="carimg" src="/css/1359532047.jpg">
</li>
<li id="13592635281366253092" class="myli" style="width:170px;height:170px;">
<div class="favs"></div>
<div class="mylimg" style="background:url(/images/th135926352813662530921.jpg) 50% 50% no-repeat;"></div>
<div class="darkbg" style="background-color: rgb(238, 28, 37); opacity: 0;"></div>
<div class="dlprice">$59.99</div>
<div class="dlmain" style="top: 153px;">
<img class="carimg" src="/css/1359532013.jpg">
</li>
Thank you in advanced for any help

You need to find the element relative to the current hovered element. you need to target the carimg and darkbg elements with the same li as the entered dlmain element. So use .closest() to find the li element and then use .find() in the li element to find the other 2 elements
Try
$(document).ready(function () {
$(document).on("mouseenter", ".dlmain", function () {
var $li = $(this).closest('li'),
src = $li.find('.carimg').attr('src'),
$darkbg = $li.find('.darkbg')
if (src == '/css/1359532013.jpg') {
$darkbg.css({
"backgroundColor": "#EE1C25"
});
} else if (src == '/css/1359532047.jpg') {
$darkbg.css({
"backgroundColor": "blue"
});
} else {}
alert(src);
});
});
Another tweak that can be applied is
$(document).ready(function () {
var backgrounds = {
'/css/1359532013.jpg': '#EE1C25',
'/css/1359532047.jpg': 'blue'
};
$(document).on("mouseenter", ".dlmain", function () {
var $li = $(this).closest('li'),
src = $li.find('.carimg').attr('src'),
$darkbg = $li.find('.darkbg');
$darkbg.css({
"backgroundColor": backgrounds[src]
});
alert(src);
});
});

if you have different '.carimg' for each divs, you should pick the specific one.
$('.carimg').attr('src') is giving you the same value for all the divs.
If the img '.carimg' and div '.darkbg' are in the current div '.dlmain', please try this:
$(document).ready(function () {
$(document).on("mouseenter", ".dlmain", function () {
var $this=$(this);
if ($this.find(‘.carimg').attr('src') == '/css/1359532013.jpg') {
$this.find(“.darkbg").css({
"backgroundColor": "#EE1C25"
});
alert($this.find('.carimg').attr('src'));
} else if ($this.find('.carimg').attr('src') == '/css/1359532047.jpg') {
$this.find(".darkbg").css({
"backgroundColor": "blue"
});
alert($this.find('.carimg').attr('src'));
} else {
alert($this.find('.carimg').attr('src'));
}
});
});

Related

passing parameters into function

I am very new to javascript and I hope to get some help simplifying the code.
I have two div box that contains 3 images each. Each div box displays an image by default (no. 1 and 4) and the mouse hover toggle a change in image (independently). See http://jsfiddle.net/hdaq9se5/6/.
The following code works just right but I am hoping to get some help simplifying the code, e.g. modify the animation function such that it takes the class of the div box as input.
$(document).ready(function () {
$("#image_two, #image_three, #image_five, #image_six").hide();
$(".image_rollover").hover(function () {
animation()
});
$(".image_rollover2").hover(function () {
animation2()
});
});
function animation() {
var $curr=$(".image_rollover img:visible");
var $next=$curr.next();
if($next.size()==0) $next=$(".image_rollover img:first");
$next.show();
$curr.hide();
}
function animation2() {
var $curr=$(".image_rollover2 img:visible");
var $next=$curr.next();
if($next.size()==0) $next=$(".image_rollover2 img:first");
$next.show();
$curr.hide();
}
Like this?
Using jquery, this is in most places (almost everywhere) the current Element. Like the Element that dispatched an event, ...
knowing this you don't need to pass any classes into animation, jquery already provides you with all you need.
$(document).ready(function() {
$(".image_box img").not(":first-child").hide();
$(".image_box").hover(animation);
});
function animation() {
var $curr = $("img:visible", this);
var $next = $curr.next();
if ($next.length === 0) {
$next = $("img:first", this);
}
$next.show();
$curr.hide();
}
.image_box {
border: 1px solid #000000;
width: 130px;
height: 80px;
overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="image_rollover image_box">
<img id="image_one" src="http://placehold.it/130x80&text=1">
<img id="image_two" src="http://placehold.it/130x80&text=2">
<img id="image_three" src="http://placehold.it/130x80&text=3">
</div>
<div class="image_rollover2 image_box">
<img id="image_four" src="http://placehold.it/130x80&text=4">
<img id="image_five" src="http://placehold.it/130x80&text=5">
<img id="image_six" src="http://placehold.it/130x80&text=6">
</div>

jQuery toggle slide animation down and up

im creating custom toggle animation on the list of bank while onlick it will toggle down and toggle up. However my code is working but it doesn't show up like an animation form. it just close and down directly without sliding slowly. Kindly advise :
I wish to toggle down for 200 height and toggle up for 102 height
jQUERY :
$(document).ready(function(){
$(".moreBankingBtn").click(function(){
$('.bank_listSetUp').toggleClass('bank_listSetTall'); // Will add/remove class on each click
});
});
HTML :
<div name="bankDisplay2" class="bank_list_main">
<ul data-bind="foreach: thirdPayBank" class="bank_list bank_listSetUp">
<li data-bind="attr:{'data-key':key, 'data-code':bankcode}, css: memberModel.netbankCssClass($data), click: $root.netBankSelectBank" data-key="工商银行" data-code="ICBC" class="bank_2"></li>
<li data-bind="attr:{'data-key':key, 'data-code':bankcode}, css: memberModel.netbankCssClass($data), click: $root.netBankSelectBank" data-key="农业银行" data-code="ABC" class="bank_3"></li>
</ul>
</div>
CSS :
.bank_listSetUp {
height: 102px;
}
.bank_listSetTall {
height: 200px;
}
You can use JQuery UI and change your code to something like
$('.bank_listSetUp').toggleClass('bank_listSetTall',500);
Here 500 is the duration of animation.
I would also suggest you to have a look at sideToggle() function http://api.jquery.com/slidetoggle/
i found an solution for this ,
jQUERY :
$(document).ready(function(){
var open = false;
var bankListMain = $("#thirdPayForm .bank_list_main");
var ul = bankListMain.find("ul");
var button = bankListMain.find("span");
button.click(function () {
open = !open;
var height;
if (open) {
height = "200px";
button.addClass("bank_hide");
} else {
height = "102px";
button.removeClass("bank_hide");
}
TweenMax.to(ul, 0.5, { css: { height: height } });
});
});
NOTE : add tweenmax.js to make it work
try slideToggle()
$(document).ready(function(){
$(".moreBankingBtn").click(function(){
$('.bank_listSetUp').slideToggle();
});
})
It doesn't look like it's animating because you're not using the jquery animate function or the slide toggle function, although since you want to animate to two different heights you can't really use the slide functions, because I believe that's just to display and hide. Maybe try this:
$(document).ready(function(){
$(".moreBankingBtn").click(function(){
If ($('.bank_list').hasClass('bank_listSetUp')){
$('.bank_list').animate({
height: 200,
}, 'slow').promise().done(function(){
$('.bank_list').removeClass('bank_listSetUp').addClass('bank_listSetTall');
});
}
else {
$('.bank_list').animate({
height: 120,
}, 'slow').promise().done(function(){
$('.bank_list').addClass('bank_listSetUp').removeClass('bank_listSetTall');
}
});
});

How can you re-render a page from JavaScript/jQuery?

I am not quite sure if that's the correct way to phrase it, but here is my problem
As you can see, pretty simple code:
<div class="first"></div>
<div></div>
What I want to achieve is:
You click on the div with the first class, it will swap that class with the sibling element
You click the sibling element, and it swaps it back, so you just swap classes around 2 elements
The problem here is it works correctly only the first time, and the second time when the new element receives the class via addClass, jQuery doesn't recognize that it contains the class by the first page load? How can I resolve this?
P.S: I made a console.log(111); just to make sure, and sure enough it triggers ONLY when I click on the black div after the first swap (the one that SHOULD NOT have the first class anymore)
To achieve this behavior, you can use delegated events http://api.jquery.com/delegate/ on elements wrapper;
$(document).delegate('.first', 'click', function(e){
e.preventDefault();
console.log(123);
$(this).removeClass('first');
$(this).siblings().addClass('first');
})
A quick and simple way to do it is this:
$(document).ready(function() {
var first = $('.first');
var second = first.next();
first.click(function(e) {
e.preventDefault();
first.removeClass('first');
second.addClass('first');
});
second.click(function(e) {
e.preventDefault();
second.removeClass('first');
first.addClass('first');
});
});
div {
background-color: black;
height: 100px;
width: 100px;
margin-bottom: 10px;
}
.first {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first"></div>
<div></div>
This way does not scale well.
Your problem was you only change when you click the $(first) which does not change when clicked it's still point to the first div.
A better way with vanilla javascript:
document.addEventListener('click', function(e) {
if (e.target.classList.contains('first')) {
e.target.classList.remove('first')
var sibling = getNextSibling(e.target) || getPreviousSibling(e.target)
if (sibling) {
sibling.classList.add('first')
}
}
})
function getNextSibling(elem) {
var sibling = elem.nextSibling
while(sibling && sibling.nodeType != 1) {
sibling = sibling.nextSibling
}
return sibling
}
function getPreviousSibling(elem) {
var sibling = elem.previousSibling
while(sibling && sibling.nodeType != 1) {
sibling = sibling.previousSibling
}
return sibling
}
All you need to do is push both items into an array, then flip between indexes on click.
var elems = [];
$(document).on("click", ".first", function(event) {
elems = elems.length == 0 ? [event.originalEvent.target, $(event.originalEvent.target).next()] : elems;
$(elems[event.originalEvent.target === elems[0] ? 1 : 0]).addClass("first");
$(elems[event.originalEvent.target === elems[0] ? 0 : 1]).removeClass("first");
});
.first {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first">x</div>
<div>y</div>

How to limit height of animation (direction top)?

I want to limit max height of animation when using arrows to switch. Trying to write a function, that will calculat height of div and +- step in px. But it's now writed to variable.
var maxfloorh = $('.floor-switch').height();
var actualh = $('.floor-switch').height();
$('.floor-switch li').click(function() {
$('#line').animate({
top: $(this).position().top
});
});
function floorarrs(numbr) {
switch (numbr) {
case 1:
//check here maxfloorh
$('#line').animate({
top: '-=18'
}, 400, function() {
maxfloorh-'18';
console.log(maxfloorh);
});
break
case 2:
//check here maxfloorh
$('#line').animate({
top: '+=18'
}, 400, function() {
maxfloorh+'18';
console.log(maxfloorh);
});
break
}
}
$('.arrw-up').click(function() {
floorarrs(1);
});
$('.arrw-dwn').click(function() {
floorarrs(2);
});​
HTML:
<div id="floors" style="margin:60px;">
<div class="arrw-up"></div>
<div class="floor-switch">
<div id='line'></div>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
<div class="arrw-dwn"></div>
</div>​
Live: http://jsfiddle.net/cxvec/2/
$('.arrw-up').click(function() {
if ($("#line").css("top") !== "0px") {
floorarrs(1);
}
});
$('.arrw-dwn').click(function() {
if ($("#line").css("top") !== ""+($("#pagination li").length-1)*18+"px") {
floorarrs(2);
}
});​
Here is the working fiddle
I have changed the logic in your arrow click function, In css the initial top attribute of the element with id=line is set to 0px
...Now whenever the top = 0px -> the div is on 1st li hence the function is not executed ans so for the down arrow...
Note: This may note be the best solution but it's one of the solutions

jQuery Multiple Panel Toggle

I'm working on a portfolio site for an iPhone developer. In this site the iPhone app icons will act as a toggle buttons for panels that describe the application. The panels animate over the main page content. To add to this, if a panel is open and another app icon is clicked the open panels will need to close and the next app will open. Currently the script I have works great for toggling a single panel, see here: http://cncpts.me/dev/
So how can change the current script so it accepts multiple ids or classes, without creating duplicate code?
Here is the jQuery that is driving the functionality for a single toggle action.
$(document).ready(function() {
$("li.panel_button").click(function(){
$("div#panel").animate({
height: "700px"
})
.animate({
height: "600px"
}, "slower");
$("div.panel_button").toggle('zoom'); return false
});
$("div#hide_button").click(function(){
$("div#panel").animate({
height: "0px"
}, "slower"); return false
});
});
Here is the HTML:
<div id="panel">
<div id="panel_contents"></div>
<img src="images/iphone.png" border="0" alt="iPhone Development">
<div class="panel_button" id="hide_button" style="display: none;">
<img src="images/collapse.png" alt="collapse" />
</div>
</div>
give the list items a rel attribute that points to the div you are trying to show/hide.
<li rel='#panel_1' class='panel_button'>
give all the div's a common class such as 'flyaway', do a hide on any div with the same class that is not currently hidden
$('.flyaway').not(':hidden').animate({ height: "0px"}, "slower");
and show the one you want
$("li.panel_button").click(function(){
$($(this).attr('rel')).animate({
height: "700px"
})
.animate({
height: "600px"
}, "slower");
$($(this).attr('rel')+" div.panel_button").toggle('zoom'); return false
});
Here is my solution:
// Plugtrade.com - jQuery Plugin :: Bounce //
// answer for http://stackoverflow.com/questions/5234732/jquery-multiple-panel-toggle
jQuery.fn.bounce = function (el, bounceheight) {
var thisdiv = this;
var owidth = thisdiv.width();
var oheight = thisdiv.height();
var trigger = $(el);
// what we want is to make a parent div and then
// get the child div's dimensions and copy it's position
// display, width and height //
// child then becomes an absolute element nested within the
// parent div.
thisdiv.wrap('<div class="bounceparent"></div>');
// let's make a hidden button
thisdiv.append('<input type=text class="bouncehide" style="display:none" />');
var thishidebtn = thisdiv.last();
var thisparent = thisdiv.parent();
thisparent.width(owidth);
thisparent.height(oheight+bounceheight);
thisparent.css('border', '1px solid #ccc');
thisparent.css('position', thisdiv.css('position'));
thisparent.css('overflow', 'hidden');
thisdiv.css('position', 'relative');
thisdiv.css('top', oheight+bounceheight);
thisdiv.css('height', '0');
var toggle = false;
thishidebtn.click(function() {
if(toggle)
{
toggle = false;
thisdiv.animate({ top: 0, height:oheight+bounceheight }).animate({ top: oheight+bounceheight, height:0 });
}
});
trigger.click(function() {
// some code //
if(!toggle)
{
// show
$('.bouncehide').click();
toggle = true;
thisdiv.animate({ top: 0, height:oheight+bounceheight }).animate({ top: bounceheight, height:oheight });
}
else
{
// hide
toggle = false;
thisdiv.animate({ top: 0, height:oheight+bounceheight }).animate({ top: oheight+bounceheight, height:0 });
}
});
// return original object so it can be chained
return thisdiv;
}; // END -> plugin :: bounce
... and here is how you use it:
$(function(){
$('#boinky').bounce('#toggle', 50);
$('#boinkyb').bounce('#toggleb', 50);
});
jsFiddle example:
http://jsfiddle.net/523NH/14/
hope this helps you.

Categories