FrozenHeart
FrozenHeart

Reputation: 20736

Unable to show a popup element when user hovers over another element

I'm trying to show a popup element when user places a mouse over an other element:

<!DOCTYPE HTML>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-2.2.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
      $(function() {
        $('#base').hover(
          function handleIn(e) {
            var popup = $('<img/>', {
              id: 'popup',
              src: 'http://placehold.it/32x32'
            });
            popup.css({
              'position': 'absolute',
              'z-index': 300,
              'left': e.pageX - 30,
              'top': e.pageY - 30
            });
            popup.mouseover(function() {
              console.log('mouseover');
            });
            popup.mouseout(function() {
              console.log('mouseout');
            });
            $('#base').append(popup);
          },
          function handleOut() {

          }
        );
      });
    </script>
  </head>
  <body>
    <img id="base" src="http://placehold.it/256x256">
  </body>
</html>

Why doesn't the popup element show up? It is added to DOM, but I don't see it.

What am I doing wrong? How can I fix it?

Upvotes: 2

Views: 60

Answers (2)

Code
Code

Reputation: 1

Try with this tooltip example:

<html>

<head>
  <link href="Styles/bootstrap.min.css" rel="stylesheet" />

</head>

<body>

  <img src="images/yourimage.jpg" class='test' data-toggle='tooltip' data-placement='right' title='your custom message' />

  <script src="Scripts/jquery-2.1.3.min.js"></script>
  <script src="Scripts/bootstrap.min.js"></script>

  <script>
    $(document).ready(function() {
      $('[data-toggle="tooltip"]').tooltip();

    });
  </script>
</body>

</html>

Upvotes: 0

jolmos
jolmos

Reputation: 1575

You can't append a child to an <img/> element. See here

Try append it to the parent

$(function() {
        $('#base').hover(
          function handleIn(e) {
            console.log("asd");
            var popup = $('<img/>', {
              id: 'popup',
              src: 'http://placehold.it/32x32'
            });
            popup.css({
              'position': 'absolute',
              'z-index': 300,
              'left': e.pageX - 30,
              'top': e.pageY - 30
            });
            popup.mouseover(function() {
              console.log('mouseover');
            });
            popup.mouseout(function() {
              console.log('mouseout');
            });
            $('#base').parent().append(popup);
          },
          function handleOut() {

          }
        );
      });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="base" src="http://placehold.it/256x256">

By the way, that way you will have a new element on every hover event.

Upvotes: 2

Related Questions