Bing
Bing

Reputation: 3171

jQuery to update actual CSS

First off: I'm aware of the jQuery.css() function, but it doesn't work in my case. I'll explain why.

I have a jQuery color picker being used to change the highlighting of a website. I want to apply that color picker to the border of an element which only shows on hover.

The jQuery.css() function only applies the CSS to elements it finds, and does not work on the :hover CSS attribute.

I've tried adding a CSS class which I toggle on the hover, but it comes back to the same problem: I'm trying to change ONLY the hover value.

There's got to be a way to do this, but I've been searching StackOverflow and Google for the better part of an hour now, so I'm invoking xkcd #627

Upvotes: 1

Views: 136

Answers (2)

Halcyon
Halcyon

Reputation: 57719

I'm adding this as an alternative answer.

If you need to dynamically change your CSS then there is something wrong with your CSS. It's very strange that you need a definition, that you can't toggle with a class and has to be generated dynamically.


Let's say you have a widget that can be in two modes: inactive or active. When it's active elements in it should respond visually to a hover event, when it's not, they shouldn't.

<div id="my-widget" class="my-widget-container">
    <div class="element">Something to look at</div>
</div>

CSS

.my-widget-container .element { background-color: #ffffff; }
.my-widget-container.active .element:hover { background-color: #00ff00; }

You switch the mode by:

$("#my-widget").addClass("active");

This will activate the :hover line for the element which now appears interactive.

If I knew more about your situation I could perhaps fix a fitting solution.


Also, jQuery.css is poorly named, perhaps jQuery.style would be a better name since that is exactly what it does.

Upvotes: 0

Binary Alchemist
Binary Alchemist

Reputation: 1620

Use the hover event to achieve the same results.

$('selector').hover( function(){
    //A function to execute when the mouse pointer enters the element.
    $(this).css('property','value');
}, function(){
    //A function to execute when the mouse pointer leaves the element.
    $(this).css('property','value');
});

Upvotes: 4

Related Questions