IF ELSE Hover statement only works on second hover - javascript

I have a menu, that when you roll over the image the image changes, unless the image has an active class attached. My problem is that the image only changes on the SECOND ROLL OVER not the FIRST. Any ideas why this is.
$("#contact").hover(function () {
if ($("#contact").is(".active")) {
$("#contact img").attr("src","Images/Menu/contact_hover.png" )
}
else {
$("#contact").hover(function () {
$("#contact img").attr("src","Images/Menu/contact_hover.png" )
},
function() {
$("#contact img").attr("src","Images/Menu/contact.png" )
});
}
});

You shouldn't be doing this with jQuery, there really is no need. Please read up on CSS Image sprites and use the css hover selector like this:
#contact {
background: url(/url/of/img) no-repeat;
}
#contact:hover {
background-position: ; // Change to desired image
}
Do this to change the background position of the image sprite you use, if you're lazy you could change the image altogther instead of bothering with sprites. You will find this method much lighter page size, as well as compatibility.

It's because you aren't making the second call to hover until the else-block runs the first time. Set all of you event handlers up in $(document).ready, and you should be good to go.

you should simplify your code - try this
$("#contact").hover(function () {
if (!$("#contact").hasClass("active")) {
$("#contact img").attr("src","Images/Menu/contact_hover.png" )
}
},
function() {
if (!$("#contact").hasClass("active")) {
$("#contact img").attr("src","Images/Menu/contact.png" )
}
});

Working example at: http://jsfiddle.net/HNGMT/
**The example uses two divs to demonstrate the difference between one with the class of active and one without. The HTML of cours is solely for demonstration purposes as well. And the jQuery selector for the contact class would be modified to reflect the id selector.
HTML:
<div class="contact"><img src="/contact.png" alt="contact inactive" /></div>
<div class="contact active"><img src="/contact.png" alt="contact active" /></div>
JavaScript:
$(".contact").hover(function () {
$(this).find("img").attr({src:"contact_hover.png", alt:"contact hover"});
}, function(){
var ele = $(this);
if(!ele.hasClass("active")){
ele.find("img").attr({ src:"contact.png", alt:"contact inactive"});
}
});

Related

Append element AFTER load

I've got this code
$(".test_init").click( function(){
var win = $(this).next(".test_wrap").find(".test_drop");
if ($(win).html().length)
$(win).empty().hide("fast");
else {
$(win).load("URL");
}
});
Which returns me some html form without close button
I wish to add close button using such method without adding it in every-single function
$('*[class*="_drop"]').change(function() {
$(this).append($('<a />', {
class: 'close-drop',
click: function(e) {
e.preventDefault();
alert("test");
}})
);
});
But nothing happens - i can't understand why close button doesn't appends
<div class="test_wrap relative">
<div class="test_drop absolute"></div>
</div>
Example: http://jsfiddle.net/fppfyey7/10/
Your problem is with your CSS, not with your JS. The button is appended but you are hidding it with your style.
For example in this fiddle I append a button with your JS code and your CSS:
Fiddle 1
Now, in this one, I just remove your absolute and relative classes:
Fiddle 2
My solution (isn't good enough, still works)
$('*[class*="_drop"]').ajaxStop(function() {
$(this).prepend('<a onclick="$(this).parent().empty().hide(\'fast\');" class="close-drop"></a>');
});
If here will be better solution, will mark it as answear!

Add class on div mouse enter mouse leave and click

What i am trying to achieve is, i want to make it work like star rating. When you enter mouse star becomes yellow, when you leave mouse it turns gray and then if you click it again becomes yellow.
Not getting how to achieve it, I have added code to show you what i have tried so far.
JSfiddle
$(".na").hover(
function () {
$(this).addClass("clickstar");
},
function () {
$(this).removeClass("clickstar");
}
);
$(".na").on("click",function(){
$(this).toggleClass("clickstar");
});
.clickstar{
background: #00A1EF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="na" style="border:1px solid #c0c0c0;border-radius:50%;width:115px;height:115px;display:inline-table;margin-right:5px;"></div>
You should consider using 2 different classes, .hoverstar and .clickstar, then :
http://jsfiddle.net/xLxbw216/1/
You would have one class for each case, which seems more logical ?
You can also make it simpler by removing .hover() method, and do it with CSS :
http://jsfiddle.net/xLxbw216/8/
I probably choose the second one, even if the first solution seems to be more "readable".
You can do it like this:
$(".na").on("click",function(){
$(this).toggleClass("clickstar");
});
Fiddle Example
You should use a different class for permanent start and hover star
I have created a working example in JSfiddle
$(".na").hover(
function () {
var $this = $(this);
if (!$this.hasClass("permstar")) {
$this.addClass("clickstar");
}
},
function () {
var $this = $(this);
if (!$this.hasClass("permstar")) {
$(this).removeClass("clickstar");
}
}
);
$(".na").on("click",function(){
$(this).toggleClass("permstar");
});
add/remove class on hover events was conflicting with on click event, so i have moved the hover functionality to css
css:
.clickstar{
background: #00A1EF;
}
.na:hover{
background: #00A1EF;
}
live demo:
http://jsfiddle.net/dreamweiver/xLxbw216/7/
Happy Coding :)

How do I apply jQuery's slideToggle() to $(this) and do the opposite to all other elements?

What I'd like to do is have all elements of class collapsible_list not displayed by default (with one exception... see below*), and then toggle their display when their parent <div class="tab_box"> is clicked. During the same click, I'd also like for every other element of class collapsible_list to be hidden so that only one of them is expanded at any given time.
*Furthermore, when the page initially loads I'd also like to check to see if an element of collapsible_list has a child a element whose class is activelink, and if there is one then I'd like that link's parent collapsible_list element to be the one that's expanded by default.
Here's some sample html code:
<style>
.collapsible_list {
display: none;
}
.collapsible_list.active {
display: block;
}
</style>
<div id="sidebar">
<div class="tab_box">
<div class="collapsible_tab">2014</div>
<div class="collapsible_list panel-2014">
1
2
3
</div>
</div>
<div class="tab_box">
<div class="collapsible_tab">2013</div>
<div class="collapsible_list panel-2013">
<a class="activelink" href="/2013/1">1</a>
2
3
</div>
</div>
</div>
And here's where I'm currently at with the javascript (although I've tried a bunch of different ways and none have worked like I'd like them to):
$(document).ready(function() {
// This looks redundant to me but I'm not sure how else to go about it.
$(".collapsible_list").children("a.activelink").parent(".collapsible_list:not(.active)").addClass("active");
$(".tab_box").click(function() {
$(this).children(".collapsible_list").toggleClass("active").slideToggle("slow", function() {
$(".collapsible_list.active:not(this)").each(function() {
$(this).slideToggle("slow");
});
});
});
});
I hope that's not too confusing, but if it is then feel free to let me know. Any help is much appreciated.
Since you have a dom element reference that needs to be excluded use .not() instead of the :not() selector
jQuery(function ($) {
// This looks redundant to me but I'm not sure how else to go about it.
$(".collapsible_list").children("a.activelink").parent(".collapsible_list:not(.active)").addClass("active").show();
$(".tab_box").click(function () {
var $target = $(this).children(".collapsible_list").toggleClass("active").stop(true).slideToggle("slow");
//slidup others
$(".collapsible_list.active").not($target).stop(true).slideUp("slow").removeClass('active');
});
});
Also, instead of using the slide callback do it directly in the callback so that both the animations can run simultaniously
Also remove the css rule .collapsible_list.active as the display is controlled by animations(slide)
Try This.
$('.collapsible_tab a').on('click', function(e){
e.preventDefault();
$('.collapsible_list').removeClass('active')
$(this).parent().next('.collapsible_list').toggleClass('active');
});
Fiddle Demo
I think your code would be less complicated if you simply remembered the previously opened list:
jQuery(function($) {
// remember current list and make it visible
var $current = $('.collapsible_list:has(.activelink)').show();
$(".tab_box").on('click', function() {
var $previous = $current;
// open new list
$current = $('.collapsible_list', this)
.slideToggle("slow", function() {
// and slide out the previous
$previous.slideToggle('slow');
});
});
});
Demo

jQuery Hide and Show Attr Src Image not switching as intended

so I searched around and edited a show/hide jquery code I found, and it works just fine except the html img attribute does not get replaced when I click on it.
My jQuery code:
<script>
$(document).ready(function() {
var button = $('#hideButton');
//check the cookie when the page loads
if ($.cookie('currentToggle') === 'hidden') {
togglePanel(button, false);
}
else {
togglePanel(button, true);
}
//handle the clicking of the show/hide toggle button
button.click(function() {
//toggle the panel as required, base on current state
if (button.attr('src') === "images/expand.gif") {
togglePanel($(this), true);
}
else {
togglePanel($(this), false);
}
});
});
function togglePanel(button, show) {
var panel = $('#panel');
if (show) {
panel.removeClass('hidden');
button.attr('src','images/collapse.gif');
$.cookie('currentToggle', '', { path: '/' });
}
else {
panel.addClass('hidden');
button.attr('src','images/expand.gif');
$.cookie('currentToggle', 'hidden', { path: '/' });
}
}
</script>
My HTML code:
<a id="hideButton" href="#"><img src="images/collapse.gif"></a>
<div id="panel">
<p>
Test
</p>
</div>
When I look at my firebug console, it shows the a href src attribute changing like so "<a ... src="extend.gif">" but not the actual "<img src="">" element itself. How do I fix this? Thank you.
button refers to the a tag, if you want to change the img src then you need to use the correct selector :
$('img',button).attr('src', 'whatever.gif');
In your code :
if (button.attr('src') === "images/expand.gif") {
should be :
if ($('img', button).attr('src') === "images/expand.gif") {
You need to do the same thing in the togglePanel function too.
to make your function work - you will want to change it to instead update the src attribute of the IMG element. not the anchor tag... you can do that like so:
function togglePanel(button, show) {
var panel = $('#panel');
if (show) {
panel.removeClass('hidden');
button.find('img').attr('src','images/collapse.gif');
$.cookie('currentToggle', '', { path: '/' });
}
else {
panel.addClass('hidden');
button.find('img').attr('src','images/expand.gif');
$.cookie('currentToggle', 'hidden', { path: '/' });
}
}
the .find('img') will return the child objects matching the selector of that parameter - for the element you call it on... in this case the anchor tag stored in your variable button...
a few things i would like to note: swapping src attributes might be effective, but you will notice a "flashing" on slower internet connections or as the image sizes gets larger. this is because you are actually having the user make a request and load that image.
the recommended way would be to do this like Diodeus said - utilizing css classes and my preference would be image sprites - that will negate the 'flashing' and minimize resource load times after the DOM has completed loading.
EDIT:
RafH has a good point! - you will also have to update the if conditional ( i overlooked ) to check the image source - not the anchors source. as he suggested
Sorry if i didn't understand your question correctly.
You want to show/hide the panel when there is clicked on the anchor, when it's clicked also the image should change.
Why not make a layout for the anchor itself and use background url to change it?
#hideButton
{
width: 25px;
height: 25px;
display: inline-block;
background: url('http://png.findicons.com/files/icons/2338/reflection/128/collapse_arrow.png');
background-size:25px 25px;
}
.reverse
{
-moz-transform: scaleY(-1);
-o-transform: scaleY(-1);
-webkit-transform: scaleY(-1);
transform: scaleY(-1);
//you can place a other image in here.
margin-bottom: 2px;
}
Now i have used mirrored image on click, you can use any image you want.
Now the jQuery code:
$(document).ready(function() {
$("#hideButton").click(function()
{
if($("#panel").is(":visible"))
{
$('#panel').slideUp('slow');
$('#hideButton').addClass('reverse');
}
else
{
$('#panel').slideDown('slow');
$('#hideButton').removeClass('reverse');
}
})
})
I use the premade animation SlideUp and slideDown. again, you can change this to your needs.
and finally the HTML:
<a id="hideButton" href="#" ></a>
<div id="panel">
<p>
Test
</p>
</div>
jsFiddle

hide one div when another is showing in jQuery?

I am trying to hide a div when another one is visible.
I have div 1 and div 2.
If div 2 is showing then div 1 should hide and if div 2 is not showing then div 1 should be visible/unhide.
The function would need to be function/document ready upon page load.
I've tried this but I'm not having any luck, can someone please show me how I can do this.
<script>
window.onLoad(function () {
if ($('.div2').is(":visible")) {
$(".div1").fadeOut(fast);
} else if ($('.div2').is(":hidden")) {
$('.div1').fadeIn(fast);
}
});
</script>
Add a class of hidden to each div, then toggle between that class using jQuery. By the way, window.onload is not a function, it expects a string like window.onload = function() {}. Also, put fast in quotations. I don't know if that's required, but that's how jQuery says to do it.
<div class="div1"></div>
<div class="div2 hidden"></div>
.hidden { display: none }
$(document).ready(function() {
if($(".div1").hasClass("hidden")) {
$(".div2").fadeIn("fast");
}
else if($(".div2").hasClass("hidden")) {
$(".div1").fadeIn("fast");
}
});
You should pass a string to the .fadeIn() and .fadeOut() methods.
Instead of .fadeIn(fast) it'll be .fadeIn("fast"). Same for .fadeOut().
And in general since you're already using jQuery it's better to wrap your code like this:
$(function () {
// Code goes here
});
It looks like you're using jquery selectors (a javascript library). If you're going to use jquery make sure the library is loaded properly by including it in the document header (google makes this easy by hosting it for you <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>)
With jQuery loaded you can do it like this
$(document).ready(function(){
if ($('.div1').is(":visible")) {
$('div2').hide();
}
else if ($('.div2').is(":visible")) {
$('div1').hide();
}
});
WORKING EXAMPLE: http://jsfiddle.net/HVDHC/ - just change display:none from div 2 to div 1 and click 'run' to see it alternate.
You can use setTimeout or setInterval to track if these divs exists
$(function() {
var interval = window.setInterval(function() {
if($('#div2').hasClass('showing')) {
$('#div1').fadeOut('fast');
}
if($('#div2').hasClass('hidden')) {
$('#div1').fadeIn('fast');
}
}, 100);
// when some time u don't want to track it
// window.clearInterval(interval)
})
for better performance
var div1 = $('#div1')
, div2 = $('#div2')
var interval ....
// same as pre code

Categories

Resources