Flo
Flo

Reputation: 540

Javascript only does only work on some places on the page

I added the javascript code directly into the html, so you are able to see what I am doing wrong.

The alert only works on the img in the div class='sandbar-one' nowhere else.

The html ouptut looks like this:

<html>
  <head> … </head>
  <body>
    <div class="header">
      <div class="sandbar">
        <a style="display:block" href="/">
          <div class="sandbar-logo">
            <div class="sandbar-one">
              <img width="300" src="/assets/123456.png" alt="123456"></img>
            </div>
          </div>
        </a>
        <div class="sandbar-left"> … 
      </div>
    </div  
    <div class="navbar navbar-inverse navbar-fixed-top"> … </div>
  </div>
  <div class="content" data-target="#sidenavbar" data-spy="scroll">
    <div class="container-fluid">
      <div class="row-fluid">
        <div class="span3"> … </div>
      <div class="span9">
        <script>
          $("img").hover(function() {
           alert("Hello World!");
           },function() {
           }) 
        </script>
        <img src="/assets/123456.png" alt="123456"></img>
        ...

the haml file:

:javascript
  $("img").hover(function() {
        alert("Hello World!");
  },function() {
  });

= image_tag("/assets/123456.png")

I tested in Firefox and Safari. The web-console shows no errors.

Upvotes: 0

Views: 45

Answers (1)

Kyle d&#39;Oliveira
Kyle d&#39;Oliveira

Reputation: 6382

This looks to be because when the javascript is executed, only that one img is loaded in the doc. Try executing the JS on page load instead

$(function(){
  $("img").hover(function() {
        alert("Hello World!");
  },function() {
  });
});

Upvotes: 3

Related Questions