Jquery how to Change or add remove CSS

Jquery how to Change or add remove CSS

image

Here we will see how to change the css of html anchor element. On ready state of the document we are adding css to hyperlink as “myLink”. As soon as mouseover or mouseout event occurs, we are chaning the css of hyperlink.

$(this).removeClass("myLink");
$(this).addClass("myLinkHover");

removeClass method removes the css class myLink. Similarly, addClass method adds css class to current element in context.

Below is css used in for this demo.

<style type="text/css">

.myLinkHover > a:hover
 {
 
  background: none repeat scroll 0 0 yellow;
  color: #FF0000;
 }
 
 .myLink
 {
  font-size: larger;
  color:green;
 }
 
 

</style>

We need to attach mouseover and mouseout event to all hyperlinks in a page.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

    <script type="text/javascript" language="javascript">
    
    $(document).ready( function (){ 
    
        $("a").addClass("myLink");
        
        $("a").mouseover(function(){
            
            $(this).removeClass("myLink");
            $(this).addClass("myLinkHover");

        });
        
        $("a").mouseout(function(){
            
            $(this).removeClass("myLinkHover");
            $(this).addClass("myLink");

        });
        
     });
    
    </script>

The actual hyperlink used in this code snippet.

<div>
            <p>
                <a href="http://www.satalaj.com">I'm the author of this code. :)njoy.</a>
            </p>
        </div>

Tags:

JQuery Change Div background Color and Text Color On ClickJQuery add/remove Class DynamicallyBasics of jqueryLearning JqueryCSS Padding Vs Margin CSS Margin Vs PaddingRemove internet explorerJQuery Select ChangeJquery Gridview Dropdownlist Selected Change Enable Disable ControlsJQuery how to change background imageCheckbox Check all GridviewJQuery On Click Change Div Content

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.