jQuery fadeColor problems - javascript

Hi I'm new to JQuery. I have an two issues that I can't figure out. I'm using copy and past code as I'm on a tight deadline.
1) When I hover over a link it doesn't fade back to the original color once I move my mouse away from the link.
2) If I move my mouse rapidly over the links they get stuck in a loop and fade in and out over and over... I know I should be able to use stop() but not sure if thats what I need.
// JavaScript Document
$(document).ready(function() {
//Grab the original BG color of the link
var originalBG = $("#nav li a").css("background-color");
//The color you want to fade too
var fadeColor = "#FFFFFF";
//Now animate on links with class = animate
$("#nav li a").hover(
function() {
$(this)
//Fade to the new color
.animate({backgroundColor:fadeColor}, 350)
//Fade back to original color
.animate({backgroundColor:originalBG}, 350)
},
function(){
}
);
});
update: from suggestions - Resolved some of my issues, but now some times if you hover over a link it doen't fade.
// JavaScript Document
$(document).ready(function() {
//Grab the original BG color of the link
var originalBG = "#351411";
//The color you want to fade too
var fadeColor = "#FFFFFF";
//Now animate on links with class = animate
$("#nav li a").hover(
function() {
//Fade to the new color
$(this).stop().animate({backgroundColor:fadeColor}, 350)
},
function(){
//Fade back to original color
$(this).stop().animate({backgroundColor:originalBG}, 350)
}
);
});

Doesn't work because the .css("background-color") returns in another color format, some like this: "rgb(18, 52, 86)".

Try this :
$("#nav li a").hover(
function() {
//Fade to the new color
$(this).animate({backgroundColor:fadeColor}, 350)
},
function(){
//Fade back to original color
$(this).animate({backgroundColor:originalBG}, 350)
}
);

Related

Changing background image referred to each menu item only by scrolling

I'm developing a wordpress theme that has a function of changing background image by hovering menu item(each menu item is attached different image). On mobile, I'd like to change background image just by scrolling so that viewers don't need to click each menu to change the background image.
This is the method I implemented to change background by hovering.
http://codepen.io/nummelin/pen/kzaso
// When any of the a's inside of sidebarContainer are hovered
$( ".sidebarContainer a" ).hover(function() {
// Removes all previous classes but keeps sidebar1
$('.sidebar1').removeClass().addClass('sidebar1');
// Splits up the URL on the current href
var URI = $(this).attr('href').split('/');
console.log(URI[2]);
// Applies the last part of the URL to sidebar1
$('.sidebar1').addClass(URI[2]);
});
Achieving with scrolling, I think I need a function that hovering menu item by its position like the image below.
Does anyone have any ideas how to achieve this? I've been exploring a plugin or sample code similar to this, but haven't found any...
Any advices would be appreciated.
Okay, so this is the code I wrote. Hope it helps. I've worked on cross-fading effect but it wasn't that easy. If someone tried please teach me how to do it.
Demo on Codepen:
http://codepen.io/bavavava/pen/rrNpaY
jQuery(function($){
'use strict';
$(document).ready(function(){
var elem = $('li.list-item'),
$listPosition = $.map(elem, function(el, i) { return $(el).offset().top; }),
$listURL = $.map(elem, function(el,i) { return $(el).find('a').attr('href'); }),
$bg = $('.container');
console.log($listPosition);
console.log($listURL);
//PRELOAD IMAGES
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
$($listURL).preload();
//SCROLL CHANGE
$(window).on('scroll', function () {
var windowScroll = $(this).scrollTop();
$.each($listPosition, function (i, pos) {
if (windowScroll >= pos) {
$bg.css('background', 'url(' + $listURL[i] + '), black no-repeat center center fixed');
}
});
});
});
});

jQuery hide show slide hover

I'm having some difficulties in one of the jQ features I've implemented. The problem is that slide animation is hiding/showing multiple times for some of the attempts. I want it to be showing only once after hovering an element.
All is working fine but sometimes is fading few times when mouse is hovering element, so if you move a mouse but you're still hover it shouldn't happened. I want it to fade every time you hover but it should animate only once per hover but sometimes is fading few extra times per one hover. Try to move a mouse between title and the content when hovering.
$(document).ready(function() {
$('.latest_module').hover(function(){
var front = $(this).children('.cb-article-meta');
var back = $(this).children('.cb-article-meta-hover');
var backh2 = $(this).children('.cb-article-meta-hover').children('h2');
var backp = $(this).children('.cb-article-meta-hover').children('p');
var img = $(this).children('.cb-grid-img');
$(front).css('display','none');
$(back).css('display','block');
$(img).addClass('latest_module_hover');
$(backh2).hide().show("slide", { direction: 'right' },800).css('padding','0 20px');
$(backp).hide().show("slide", { direction: 'left' }, 800).css('padding','0 20px');
},function(){
var front = $(this).children('.cb-article-meta');
var back = $(this).children('.cb-article-meta-hover');
var img = $(this).children('.cb-grid-img');
$(front).css('display','block');
$(back).css('display','none');
$(img).removeClass('latest_module_hover');
});
});
Testing on jsfiddle
Thanks,
If your problem is that you only want hover to run the first time you can just unbind it when it enters with this $(this).unbind('mouseenter mouseleave')
$(document).ready(function() {
$('.latest_module').hover(function(){
$(this).unbind('mouseenter mouseleave')
...
http://jsfiddle.net/bgsx23nc/12/
EDIT:
or as suggested by Guruprasad Rao only on leave
...
$(img).removeClass('latest_module_hover');
$(this).unbind('mouseenter mouseleave')
});
});
http://jsfiddle.net/Guruprasad_Rao/bgsx23nc/13/
Just add a class to the sliding element and then from next time check if it has class already and if yes don't do anything like one below:
DEMO
$(document).ready(function() {
$('.latest_module').hover(function(){
if(!$(this).hasClass('hoverDone')) //check if it has class and if no then
{
$(this).addClass('hoverDone'); //add class once hover done
var front = $(this).children('.cb-article-meta');
var back = $(this).children('.cb-article-meta-hover');
var backh2 = $(this).children('.cb-article-meta-hover').children('h2');
var backp = $(this).children('.cb-article-meta-hover').children('p');
var img = $(this).children('.cb-grid-img');
$(front).css('display','none');
$(back).css('display','block');
$(img).addClass('latest_module_hover');
$(backh2).hide().show("slide", { direction: 'right' },800).css('padding','0 20px');
$(backp).hide().show("slide", { direction: 'left' }, 800).css('padding','0 20px');
}
},function(){
var front = $(this).children('.cb-article-meta');
var back = $(this).children('.cb-article-meta-hover');
var img = $(this).children('.cb-grid-img');
$(front).css('display','block');
$(back).css('display','none');
$(img).removeClass('latest_module_hover');
});
});

Want to show navbar smooth after scroll > 10

i have created a navigation and when scrolls down after 10 it changes its background color but i want to make it a little smooth to change its bg-color.
my jquery navigation code
var a = $(".navbar-default").offset().top;
$(document).scroll(function(){
if($(this).scrollTop() > 10)
{
$('.navbar-default').css({"background":"#fff"});
}
else
{
$('.navbar-default').css({"background":"transparent"});
}
});
the code i was trying but its not working
$('.navbar-default').css({"background":"#fff"}).show("slow");
When transitioning CSS properties you use jQuery animate. However, you cannot transition non-numeric properties like colors. To do this you can use jquery.color.js :
(function(h,m){function n(a,b,c){var d=r[b.type]||{};if(null==a)return c||!b.def?null:b.def;a=d.floor?~~a:parseFloat(a);return isNaN(a)?b.def:d.mod?(a+d.mod)%d.mod:0>a?0:d.max<a?d.max:a}function s(a){var b=f(),c=b._rgba=[],a=a.toLowerCase();j(v,function(d,g){var e,i=g.re.exec(a);e=i&&g.parse(i);i=g.space||"rgba";if(e)return e=b[i](e),b[k[i].cache]=e[k[i].cache],c=b._rgba=e._rgba,!1});return c.length?("0,0,0,0"===c.join()&&h.extend(c,o.transparent),b):o[a]}function p(a,b,c){c=(c+1)%1;return 1>6*c?
a+6*(b-a)*c:1>2*c?b:2>3*c?a+6*(b-a)*(2/3-c):a}var w=/^([\-+])=\s*(\d+\.?\d*)/,v=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,parse:function(a){return[a[1],a[2],a[3],a[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,parse:function(a){return[2.55*a[1],2.55*a[2],2.55*a[3],a[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,parse:function(a){return[parseInt(a[1],16),parseInt(a[2],16),
parseInt(a[3],16)]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])/,parse:function(a){return[parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16),parseInt(a[3]+a[3],16)]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(a){return[a[1],a[2]/100,a[3]/100,a[4]]}}],f=h.Color=function(a,b,c,d){return new h.Color.fn.parse(a,b,c,d)},k={rgba:{props:{red:{idx:0,type:"byte"},green:{idx:1,type:"byte"},blue:{idx:2,type:"byte"}}},hsla:{props:{hue:{idx:0,
type:"degrees"},saturation:{idx:1,type:"percent"},lightness:{idx:2,type:"percent"}}}},r={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},t=f.support={},u=h("<p>")[0],o,j=h.each;u.style.cssText="background-color:rgba(1,1,1,.5)";t.rgba=-1<u.style.backgroundColor.indexOf("rgba");j(k,function(a,b){b.cache="_"+a;b.props.alpha={idx:3,type:"percent",def:1}});f.fn=h.extend(f.prototype,{parse:function(a,b,c,d){if(a===m)return this._rgba=[null,null,null,null],this;if(a.jquery||a.nodeType)a=
h(a).css(b),b=m;var g=this,e=h.type(a),i=this._rgba=[];b!==m&&(a=[a,b,c,d],e="array");if("string"===e)return this.parse(s(a)||o._default);if("array"===e)return j(k.rgba.props,function(d,c){i[c.idx]=n(a[c.idx],c)}),this;if("object"===e)return a instanceof f?j(k,function(c,d){a[d.cache]&&(g[d.cache]=a[d.cache].slice())}):j(k,function(d,c){var b=c.cache;j(c.props,function(d,e){if(!g[b]&&c.to){if(d==="alpha"||a[d]==null)return;g[b]=c.to(g._rgba)}g[b][e.idx]=n(a[d],e,true)});if(g[b]&&h.inArray(null,g[b].slice(0,
3))<0){g[b][3]=1;if(c.from)g._rgba=c.from(g[b])}}),this},is:function(a){var b=f(a),c=!0,d=this;j(k,function(a,e){var i,h=b[e.cache];h&&(i=d[e.cache]||e.to&&e.to(d._rgba)||[],j(e.props,function(a,d){if(null!=h[d.idx])return c=h[d.idx]===i[d.idx]}));return c});return c},_space:function(){var a=[],b=this;j(k,function(c,d){b[d.cache]&&a.push(c)});return a.pop()},transition:function(a,b){var c=f(a),d=c._space(),g=k[d],e=0===this.alpha()?f("transparent"):this,i=e[g.cache]||g.to(e._rgba),h=i.slice(),c=c[g.cache];
j(g.props,function(a,d){var g=d.idx,e=i[g],f=c[g],j=r[d.type]||{};null!==f&&(null===e?h[g]=f:(j.mod&&(f-e>j.mod/2?e+=j.mod:e-f>j.mod/2&&(e-=j.mod)),h[g]=n((f-e)*b+e,d)))});return this[d](h)},blend:function(a){if(1===this._rgba[3])return this;var b=this._rgba.slice(),c=b.pop(),d=f(a)._rgba;return f(h.map(b,function(a,b){return(1-c)*d[b]+c*a}))},toRgbaString:function(){var a="rgba(",b=h.map(this._rgba,function(a,d){return null==a?2<d?1:0:a});1===b[3]&&(b.pop(),a="rgb(");return a+b.join()+")"},toHslaString:function(){var a=
"hsla(",b=h.map(this.hsla(),function(a,d){null==a&&(a=2<d?1:0);d&&3>d&&(a=Math.round(100*a)+"%");return a});1===b[3]&&(b.pop(),a="hsl(");return a+b.join()+")"},toHexString:function(a){var b=this._rgba.slice(),c=b.pop();a&&b.push(~~(255*c));return"#"+h.map(b,function(a){a=(a||0).toString(16);return 1===a.length?"0"+a:a}).join("")},toString:function(){return 0===this._rgba[3]?"transparent":this.toRgbaString()}});f.fn.parse.prototype=f.fn;k.hsla.to=function(a){if(null==a[0]||null==a[1]||null==a[2])return[null,
null,null,a[3]];var b=a[0]/255,c=a[1]/255,d=a[2]/255,a=a[3],g=Math.max(b,c,d),e=Math.min(b,c,d),i=g-e,h=g+e,f=0.5*h;return[Math.round(e===g?0:b===g?60*(c-d)/i+360:c===g?60*(d-b)/i+120:60*(b-c)/i+240)%360,0===f||1===f?f:0.5>=f?i/h:i/(2-h),f,null==a?1:a]};k.hsla.from=function(a){if(null==a[0]||null==a[1]||null==a[2])return[null,null,null,a[3]];var b=a[0]/360,c=a[1],d=a[2],a=a[3],c=0.5>=d?d*(1+c):d+c-d*c,d=2*d-c;return[Math.round(255*p(d,c,b+1/3)),Math.round(255*p(d,c,b)),Math.round(255*p(d,c,b-1/3)),
a]};j(k,function(a,b){var c=b.props,d=b.cache,g=b.to,e=b.from;f.fn[a]=function(a){g&&!this[d]&&(this[d]=g(this._rgba));if(a===m)return this[d].slice();var b,q=h.type(a),k="array"===q||"object"===q?a:arguments,l=this[d].slice();j(c,function(a,d){var b=k["object"===q?a:d.idx];null==b&&(b=l[d.idx]);l[d.idx]=n(b,d)});return e?(b=f(e(l)),b[d]=l,b):f(l)};j(c,function(d,b){f.fn[d]||(f.fn[d]=function(c){var e=h.type(c),g="alpha"===d?this._hsla?"hsla":"rgba":a,f=this[g](),j=f[b.idx];if("undefined"===e)return j;
"function"===e&&(c=c.call(this,j),e=h.type(c));if(null==c&&b.empty)return this;"string"===e&&(e=w.exec(c))&&(c=j+parseFloat(e[2])*("+"===e[1]?1:-1));f[b.idx]=c;return this[g](f)})})});f.hook=function(a){a=a.split(" ");j(a,function(a,c){h.cssHooks[c]={set:function(a,b){var e,i="";if("string"!==h.type(b)||(e=s(b))){b=f(e||b);if(!t.rgba&&1!==b._rgba[3]){for(e="backgroundColor"===c?a.parentNode:a;(""===i||"transparent"===i)&&e&&e.style;)try{i=h.css(e,"backgroundColor"),e=e.parentNode}catch(j){}b=b.blend(i&&
"transparent"!==i?i:"_default")}b=b.toRgbaString()}try{a.style[c]=b}catch(k){}}};h.fx.step[c]=function(a){a.colorInit||(a.start=f(a.elem,c),a.end=f(a.end),a.colorInit=!0);h.cssHooks[c].set(a.elem,a.start.transition(a.end,a.pos))}})};f.hook("backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor");h.cssHooks.borderColor={expand:function(a){var b={};j(["Top","Right","Bottom","Left"],function(c,d){b["border"+
d+"Color"]=a});return b}};o=h.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"}})(jQuery);
GitHub link here.
Just copy the entire code, place it into a normal text file and include it after jQuery.
Now, you can animate colour based properties like this :
var a = $(".navbar-default").offset().top;
$(document).scroll(function () {
if ($(this).scrollTop() > 10) {
$('.navbar-default').css("position","fixed");
$('.navbar-default').stop().animate({
'background-color': "black"
},500);
} else {
$('.navbar-default').css("position","relative");
$('.navbar-default').stop().animate({
'background-color': "red"
},500);
}
});
See working jSFiddle here.

jQuery FadeIn, FadeOut spamming bug

I have typed some code to fade in and out some divs including a navigator.
I've noticed a bug when you click the navigator fast and try to change between divs very fast by spamming the buttons, the div's will be bugged and if you will inspect the code, you will see that the divs are fading in up to 0.5 opacity, or sometimes even 0.12 and fades out to 0.0 up to 0.09 or something like that.
This is my code:
$(document).ready(function(){
var currentDiv = $("#fading_divs div:first");
currentDiv.css("display","block");
var divN = $("#fading_divs div").length;
var fadeInterval;
for(i=0; i<divN; i++){
$('<span />').text(i+1).appendTo('#fade_nav');
}
$('#fade_nav span').eq(0).addClass('active');
$('#fade_nav span').click(function(){
clearInterval(fadeInterval);
$('#fade_nav span').removeClass('active').eq( $(this).index() ).addClass('active');
currentDiv.fadeOut({duration:1000,queue:false});
currentDiv = $("#fading_divs div").eq( $(this).index() );
currentDiv.fadeIn({duration:1000,queue:false});
anim();
});
function anim() {
fadeInterval = setInterval(function(){
currentDiv.fadeOut({duration:1000,queue:false});
if(currentDiv.next().length)
currentDiv = currentDiv.next();
else
currentDiv = currentDiv.siblings().first();
$('#fade_nav span').removeClass('active').eq( currentDiv.index() ).addClass('active');
currentDiv.fadeIn({duration:1000,queue:false});
}, 4000);
}
anim();
});
Here is a fiddle: http://jsfiddle.net/b5PfE/
try to spam the nav buttons until you will see that the divs are barely fading in or out.
Any suggestion about how to fix it?
This is how I usually solve issues like that:
Add a class to your #fade_nav span of "activated"
Use $('.activated').live('click', function (event) { // }); to start your function
Within that function, first remove the activated class from #fade_nav. This will prevent the buttons from being clickable during your animation.
At the end of the function, add the .activated class back on so the buttons are clickable once more.

Create Jquery Drop down using Divs and maintaing dual hover

What I'm trying to do is to fade in a div by rolling over a link. Once your mouse is over the link, you're able to mouse around the div that just faded in and you can click links inside the div.
Currently I have four links and each have a div with links and images in. On hover of the link the div fades in below the link then you can move your mouse over the div and use the images + links within. On roll out of the link or the div, it should fade out. Also, if you move your mouse to another main navigation link it should fade out the previous and fade in the new div.
The problem seems to be that the previous DIV will sometimes not fade out if you rapidly move to next link. I'm drawing a blank, any ideas?
Problem solved, answer is here: http://jsfiddle.net/UkneJ/3/
This is what I'm working with: http://jsfiddle.net/DemhU/17/
$('#div1, #div2, #div3, #div4').hide();
var is_over;
var hide_dropnav = function(a) {
setTimeout(function() {
if (is_over) {
return;
} else {
var a_name = $(a).attr('data-name');
$('#' + a_name).fadeTo(250, 0);
$('#nav li a').removeClass('active');
}
}, 10);
}
$('#nav li a').hover(function() {
var elem_name = $(this).attr('data-name');
$('#' + elem_name).stop(true,true).fadeTo(150, 1);
is_over = true;
$('#nav li a').removeClass('active');
$(this).addClass('active');
var that = this;
hide_dropnav(that);
}, function(){
is_over = false;
hide_dropnav(this);
});
$('#div1, #div2, #div3, #div4').hover(function() {
is_over = true;
}, function() {
is_over = false;
});
There are a lot of ways to do this, but I threw together a quick working example of the method I've used before:
http://jsfiddle.net/UkneJ/
In this example, I'm binding hover to both the A and the DIV, and using a slight delay to check is "is either element hovered?" state.
You can also just bind hover to the wrapping LI, which makes things much simple. This only works if both your link and your div are contained in each LI, though:
http://jsfiddle.net/UkneJ/1/
possible without javascript: http://jsfiddle.net/XENww/

Categories

Resources