April 21, 2013

Retrieving "Active" state CSS with jQuery

Majed’s Questions:

Is it possible to retrieve the :active state CSS with jQuery? The reason why I ask this is because I’m trying to make dynamic code so I don’t have to always tweak the jQuery when stylizing an element.

Edit

To elaborate, I don’t want to .addClass() or .removeClass() because the class might not be the same for every element being affected by my jQuery code.

Edit 2

Let me further explain what I’m trying to do.

I’m trying to create a plugin for my own personal use, and instead of having to tweak the code every time I have a new element that will be affected by the plugin, I want it to grab what’s already in the CSS so I won’t have to lose time. What I’m trying to do is create a button with an :active state, and when the user clicks the button, it will “freeze” at that state (my thoughts are to grab the CSS from that state and put them in the .css() command). Now, the reason why I don’t want to .addClass() or removeClass() because the :active state is going to differ from one button to another.

Pseudo classes such as :active cannot be retrieved and manipulated from jQuery. Instead of trying to get this work, I have a workaround to solve this problem.

First create a style container with only the :active part. For example:

<style id="activeLink">
    a:active { color: #f00; }
</style>

Now you can manipulate this using the jQuery, to retrieve current styles

var curStyle = $("#activeLink").html();

To modify the style

$("#activeLink").html("a:active { color: #000; }");

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!