Search code examples
javascriptonmouseoveronmouseout

Change Multiple Inline Styles using Javascripts OnMouse Over, OnMouse Out, Enter Key Change


Can someone help point me in the direction of changing multiple inline styles using javascript suchas: OnMouseOver, OnMouseOut, and then a enter key change?

I have 2 onclick mouse over / out things that need to happen and then an after Enter key pushed state that needs to change the graphic out to a loading graphic?

Before Mouse Over State:

src="images/transparent_100x100.png" style="background:url(/images/image_giblets_20x.png) no-repeat scroll right -414px transparent"

Mouse Over State - Change right to left:

src="images/transparent_100x100.png" style="background:url(/images/image_giblets_20x.png) no-repeat scroll left -414px transparent"

Once clicked to begin search - change the image to this and remove [style details]:

src="images/loading2.gif"

Here is what I tried so far for just the OnMouseOver/Out part.

<img id="nb_search_magglass" alt="Search" border="0"
onmouseover="document.getElementById('nb_search_magglass').style.background: url(/images/image_giblets_20x.png) no-repeat scroll left -414px transparent;"

onmouseout="document.getElementById('nb_search_magglass').style=.background: url(/images/image_giblets_20x.png) no-repeat scroll right -414px transparent;"

style="background:url(/images/image_giblets_20x.png) no-repeat scroll right -414px transparent" src="images/transparent_100x100.png" width="23px" height="23px" />

Solution

  • You can use jQuery. Here's a detailed list of events you can use: http://api.jquery.com/category/events/

    The idea would be:

    <html>
    <head>
      <script>
      jQuery(document).ready(function() {
          $("img.wanna-change").mouseover(function() {
             // this this here is the <img> object. Here I make it into a
             //   jQuery object but you can put any javascript code here
             $(this).attr("style", "background:url() no-repeat scroll; width: 20px;")
          });
      </script>
    </head>
    <body>
      <img class="wanna-change" src="something" />
      <img class="wanna-change" src="something-else" />
    </body>
    </html>
    

    On the other hand, I wouldn't use javascript to do this, I'd do it from css like so:

    img {
        your-normal-style;
    }
    img:hover {
        your-hover-style;
    }
    img.searching {
        your-searching-style;
    }
    

    and change that piece of jQuery to just catch the click, do the search AJAX call, and then

    $(this).addClass("searching");
    

    and probably

    $(this).removeClass("searching");
    

    when the search is done