Jquery toggleClass issue - javascript

initially hovering works and the "over" class is added on mouseenter and removed on mouseout, but after doing some hovering over paragraphs with class="risk" the toggle class becomes stuck, and mouseover removes it instead of adding the class (opposite of expected functionality)
//changes risk map point color when hovering over
// risk list item on right hand side
$("p.risk").bind("mouseenter mouseleave", function(e){
$(this).toggleClass("over");
var pointId= "ctl00_ContentPlaceHolderMain_" + $(this).attr("id");
var pointArray = $(".riskMapPoint");
for(i=0; i<pointArray.length; i++){
if( $(pointArray[i]).attr("id") == pointId )
{
$(pointArray[i]).css({'background-color' : '#3D698A'});
$(pointArray[i]).css({'z-index' : '2'});
}
else
{
$(pointArray[i]).css({'background-color' : '#000000'});
$(pointArray[i]).css({'z-index' : '1'});
}
}
});

Why not simply use the hover method? Set the background/z-index of the associated point on hover and remove it when leaving the element.
$('p.risk').hover(
function() {
var $this = $(this);
$this.addClass('over');
$('.riskMapPoint')
.find('[id$=' + $this.attr('id') + ']')
.css({ 'background-color' : '#3D698A', 'z-index' : 2 } );
},
function() {
var $this = $(this);
$this.removeClass('over');
$('.riskMapPoint')
.find('[id$=' + $this.attr('id') + ']')
.css({ 'background-color' : '#000000', 'z-index' : 1 } );
}
});

Why not have two separate functions for mouseenter and mouseleave. Have mouseenter add the class and mouseleave remove the class. I think the problem is that if for example the mouseleave event is not fired (browser looses focus I think can cause this) then the mouseenter function will remove the class instead of adding it.

Try not to change css values in code but instead use jquery to addClass and removeClass. I had a hover problem a couple months ago and applying css classes instead of manually changing values fixed my problem.

Related

getting current clicked element and add attribute in jquery Is not for working for child elements

FIDDLE DEMO
I am trying to get the clicked element in the DOM Tree, and where i have clicked in the same element the attribute has to be appended, again if i click the same element it has to check if its present it has to be removed.
Current Behavior : when i click an element i am getting the element (p, div, option,etc.,) in alert., but the ISSUE is when i am adding attribute its getting added to the parent div.
Updated : when Ajax happens the attributes are being removed.
JS :
$('#search-refine-bar').on('click', function(e) {
var eventNode = e.target.nodeName;
var refineChil = $('#search-refine-bar').children();
var refineHasAttr = $('refineChil').attr({
tabindex: "-1",
focus: "focus"
});
alert(eventNode)
if ($("#search-refine-bar").is('[focus]')) {
alert(eventNode + " ----- " + 'attribute exists should be removed');
$(this).removeAttr('tabindex focus style')
} else {
alert(eventNode + " ----- " + ' NO attribute exists...adding attribute');
$(this).attr({
tabindex: "-1",
focus: "focus"
}).css({
"border": "1px solid #f00"
});
}
});
Appreciate your help :)
You need to add/remove the attribute from e.target.
Inside the event handler this refers the target of the handler(in this case #search-refine-bar), but since you want the actual element that was clicked you can use the target property of the event
$(e.target).removeAttr('tabindex focus style')
Demo: Fiddle
Dont do it that way. Use jquery toggle function or add a class if it has the properties. Its the best approach.

adding fadeTo Method in Script

I want to add fadeTo to this code snippet. When this adds the class current i want it to fade in. But I don't know how to solve, and where I've have to put the fadeTo(); parameter.
$(this).bind("click", function() {
navClicks++;
$(this).addClass('current').parents('ul').find('a').not($(this)).removeClass('current');
offset = - (panelWidth*z);
alterPanelHeight(z);
currentPanel = z + 1;
$('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
if (!settings.crossLinking) { return false }; // Don't change the URL hash unless cross-linking is specified
});
I'm not exactly sure which DOM element you're looking to fadeTo(), but take a look at this jsfiddle:
http://jsfiddle.net/37XEp/1/
i have a class "current" which i add on click. in your example the "click me" and i want to fade in the green color of your "Click me" text slowly... nevermind the pikachu!

jQuery change hover on color, then return back to original color

I've got some buttons on a page whose color is changed via jQuery, illustrating which one's active. I'd like to add a color change ONLY when hovering, after which it's returned to the original color (which is dictated by jQuery) when left.
I first used css: .showlink li:hover {color:#aaa;} which works appropriately except for that when the pages are switched and jQuery changes the colors, it superceeds the CSS.
Then I decided to use simple jQuery that says when something's hovered on, change it's color. this doesn't completely work because it permanently changes the color. To mitigate this, I added in a bit to the function that returns it to a different color.
is there some way I can return it to the original color from before it was changed on hover?
// Changes color on hover
$(function() {
$('.showlink').hover(function(){
$(this).css('color', '#aaa');
},
function(){
$(this).css('color', '#f3f3f3');
});
});
//Changes color depending on which page is active, fades that page in
$(function(){
$('#show_one').css('color', '#ffcb06');
$('#two, #three').hide();
});
$('.showlink').click(function(){
$('.showlink').css('color', '#f3f3f3');
$(this).css('color', '#ffcb06');
var toShow = this.id.substr(5);
$('div.page:visible').fadeOut(600, function(){
$('#' + toShow).fadeIn(600);
});
});
.showlink li:hover {color:#aaa !important;}
will superceede everything else.
I'd recommend using an array to record the original color value, and use that in the mouseleave (second) function of hover():
var originalColors = [];
// Changes color on hover
$(function() {
$('.showlink').hover(function(){
originalColors[$(this).index('.showlink')] = $(this).css('color');
$(this).css('color', '#aaa');
},
function(){
$(this).css('color', originalColors[$(this).index('.showlink')]);
});
});
JS Fiddle demo.
You could also use addClass() and removeClass():
// Changes color on hover
$(function() {
$('.showlink').hover(function(){
$(this).addClass('hovered');
},
function(){
$(this).removeClass('hovered');
});
});
JS Fiddle demo.
Which would simply use CSS to apply the changed colour, and wouldn't require any kind of local storage of the CSS colour to reimplement it on mouseleave.
when I have issues like this where original data on an element is lost, I call myElement.setAttribute("oldcolor",myElement.style.color) before changing it, and when I want to revert, I just set it to that. myElement.style.color = myElement.getAttribute("oldcolor")
Although it may be best to use CSS for this, there are times when JavaScript is preferred for one reason or another. Even if CSS is always batter, the concept below should help you with other things in the future as well. So, that being said:
On hover, before changing color, get the current color and store it in the element's data. On hover-out, read that color back.
Demo:
http://jsfiddle.net/JAAulde/TpmXd/
Code:
/* Changes color on hover */
$( function()
{
$( '.showlink' ).hover(
function()
{
/* Store jQuerized element for multiple use */
var $this = $( this );
$this
/* Set the pre-color data */
.data( 'prehovercolor', $this.css( 'color' ) )
/* Set the new color */
.css( 'color', '#aaa' );
},
function()
{
/* Store jQuerized element for multiple use */
var $this = $( this );
$this
/* Set the color back to what is found in the pre-color data */
.css( 'color', $this.data( 'prehovercolor') );
}
);
} );
Use jQuery .mouseout() this is like the inverse of .hover(). If the mouse goes over .showlink element and then off of it again, .mouseout() is called.
$('.showlink').hover(function(){
$(this).css('color', '#aaa');
}
$('.showlink').mouseout(function(){
$(this).css('color', '#bbb');
}

Javascript change style on mouse click

i have a little jquery script :
$('.product_types > li').click(function() {
$(this)
.css('backgroundColor','#EE178C')
.siblings()
.css('backgroundColor','#ffffff');
// $('.product_types > li').removeClass(backgroundColor);
});
that colors me a div onclick. The problem is that i want only the last element clicked to be colored. And i dont know can i remove the style (the css style) after every click ?
thank you
I would use a css class like .lastClicked and using jquery to remove all instances of .lastClicked when a new element is clicked.
.lastClicked{ background-color:#EE178C; }
.lastClicked (siblingName) { background-color: #ffffff; }
your jquery code would look something like:
$('.product_types > li').click(function() {
$(".lastClicked").removeClass("lastClicked");
$(this).addClass("lastClicked");});
You can store lastly clicked element in global variable, and on click reset its color :
var lastElm = null
$('.product_types > li').click(function() {
if( lastElm ) $(lastElm).css('backgroundColor','#[Your original color]')
lastElm = this;
$(this)
.css('backgroundColor','#EE178C')
.siblings()
.css('backgroundColor','#ffffff');
// $('.product_types > li').removeClass(backgroundColor);
});
You need a variable that store the actual colored div and remove style on it. Something like this (not tested) should do the trick :
(function(){
var coloredDiv = null;
$('.product_types > li').click(function() {
var item = $(this);
if(coloredDiv != null) coloredDiv.removeClass('someCSSClassThatColorMyDiv');
item.addClass('someCSSClassThatColorMyDiv');
coloredDiv = item;
});
})();
NB: I also suggest to use CSS class instead of manualy set the CSS property in the Javascript. This leads to better separating of the code logic and displaying.
I also put the whole stuff in a closure so the variable cannot be overriden by some other script by mistake.

jquery click .addClass issue

Hi i have been having trouble all day with this, it almost works but not quite, i need the corresponding p (#p-1 etc) to stay highlighted once the thumb nail is clicked. I have used a Plug in for an image slider which i have customized slightly and the mouseover and mouseleave events are working fine but the click event doesn't appear to add the class to the target paragraph.
Example on jsfiddle http://jsfiddle.net/RVYnb/7/
The relevant jQuery is written inline on the example.
this is driving me crazy, please help!
The error is in the image slider plugin. It also binds to the click event in the code.
Here's the relevant code part in the plugin:
jQuery("div#thumbSlider" + j + " a").each(function(z) {
jQuery(this).bind("click", function(){
jQuery(this).find("p.tmbrdr").css({borderColor: settings.thumbsActiveBorderColor, opacity: settings.thumbsActiveBorderOpacity});
jQuery(this).parent().parent().find("p.tmbrdr").not(jQuery(this).find("p.tmbrdr")).css({borderColor: settings.thumbsBorderColor, opacity: settings.thumbsBorderOpacity});
var cnt = -(pictWidth*z);
(cnt != container.find("ul").css("left").replace(/px/, "")) ? container.find("span.typo").animate({"opacity": 0}, 250) : null ;
container.find("ul").animate({ left: cnt}, settings.easeTime, settings.easeFunc, function(){container.find("span.typo").animate({"opacity": settings.typoFullOpacity}, 250)});
return false;
});
});
The problem is the "return false" at the end. It stopps the propagation to other click events.
Change the code to the following:
Query(this).bind("click", function(e){
jQuery(this).find("p.tmbrdr").css({borderColor: settings.thumbsActiveBorderColor, opacity: settings.thumbsActiveBorderOpacity});
jQuery(this).parent().parent().find("p.tmbrdr").not(jQuery(this).find("p.tmbrdr")).css({borderColor: settings.thumbsBorderColor, opacity: settings.thumbsBorderOpacity});
var cnt = -(pictWidth*z);
(cnt != container.find("ul").css("left").replace(/px/, "")) ? container.find("span.typo").animate({"opacity": 0}, 250) : null ;
container.find("ul").animate({ left: cnt}, settings.easeTime, settings.easeFunc, function(){container.find("span.typo").animate({"opacity": settings.typoFullOpacity}, 250)});
e.preventDefault();
});
});
and it should work.
It looks to me, according to the "fiddle", that your "click" event isn't working on your thumbnails. It's never adding the "clicked" class to your .
I threw an "alert" into this:
$("#t1").live("click", function() {
alert('clicking');
$("#p-1").addClass("clicked").addClass("highlighted");
});
and the alert never popped.

Categories