2

Is it possible with jquery to add new style declarations?

For example, pass:

{ "body": { "font-size": "12px" }, "table": { "xyz": "123" } }

etc etc

to a function I don't know without having to select those elements and do it like this:

$('body').css({"font-size": "12px"});
$('table').css({"xyz": "123"});

And second part of the question, is it possible to set css for the :hover pseudo class with jquery or do I need to use the .hover() function? If possible I just want css applied and not have to deal with on mouse in / out functions.

$('#element').find('a.thumbnail:hover').css({'background-color': '#efefef' });

does not work.

Thanks, Wesley

1

5 Answers 5

5

You can alter the stylesheet itself with pure javascript through the document.stylesheets collection. see more here: http://www.howtocreate.co.uk/tutorials/javascript/domstylesheets

You can also use the jQuery plugin jRule to accomplish the same results: http://flesler.blogspot.com/2007/11/jqueryrule.html

Sign up to request clarification or add additional context in comments.

Comments

4

Answer to part 1:

You would have to define a function to do that - try something like this:

function styleit(json)
{
    //loop through the json
    $.each(item, function(i, style){
      //apply styles
      $(i).css(styles);
    }
}

Answer to part 2:

I would put the css declaration in a class like:

.active a.thumbnail:hover { background-color: #efefef; }

Then use javascript to toggle the class in a parent element's context

$('#element').addClass('active');

Comments

0

For the first part, you are correctly adding styles to the body and table tags.

For the second part, this solution, while using .hover() seems to be a easier solution:

$('#element').hover(function() {
    $(this).css({'background-color': '#efefef' });
});

2 Comments

hover() has 2 functions, background will not revert back.
Thank you for this, I have always just used a callback and didn't actually know that it wouldn't revert back.
0

Try this :

$('a.thumbnail').hover(
    function(){
        $(this).css({'background-color':'#efefef'});
    },
    function(){
        $(this).css({'background-color':'normal-color'});
    }
);

Example : http://jsfiddle.net/jfhpg/1/

Hope it helps.

Comments

-1

You have to do it by selecting the dom element only. Also in order to set the hover styles you have to either set the styles using css or add/remove class names.

2 Comments

@Phil - He is asking whether it is possible to do it the way he wants. I answered it is not possible he has to do the way he is doing. I think I shouldn't get down vote for this. I didnt answer anything wrong here.
You didn't answer it wrong, but it's a complete waste of an answer. I'll remove the down vote if you edit it...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.