Loyal_Burrito
Loyal_Burrito

Reputation: 125

jQuery - How to add a new div at bottom of DOM

I need to add a div when the mouse goes over an image on the screen, which creates a larger version of the same image at the bottom of the viewport. Unfortunately, I don't think I am doing this correctly, as it is not recognising some elements when I'm creating the new node for the div. It is not recognising the alt of the image.

This is my jQuery code:

$(function(){
  $(".img-responsive").mousemove(function(e) {
    $("main").append(
      var alt = $(this).attr("alt");
      var src = $(this).attr("src");
      var newsrc = src.replace("small","medium");

      var preview= $('<div id="preview"></div>');
      var image = $('<img src="' + newsrc + '">');
      var caption = $('<p>' + alt + '</p>');
    );
  });
});

This is the HTML:

<img src="images/5857298322.jpg" alt="image 1" class="img-responsive">
<p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.  </p>
<p><button class="btn btn-primary" type="button">View details</button></p>

Upvotes: 0

Views: 113

Answers (2)

Vishnu Baliga
Vishnu Baliga

Reputation: 413

You are unable to get the alt of the image because, the $this reference you had made was wrong. According to your code the $this is referring the $("main") element instead of image. Also selectors should be either class/id/tag, $("main") is not a valid HTML tag.

Overall I find your Jquery syntax is wrong, But I can understand what you are trying to achieve. I've created a working fiddle, I hope this solves your problem.

Fiddle link: https://jsfiddle.net/Baliga/ub83xezo/21/

Upvotes: 0

Patrick Hund
Patrick Hund

Reputation: 20236

The syntax of your JavaScript code is invalid. You are calling the append method of a jQuery element, which expects an HTML string, DOM element or text, array or another jQuery element.

Instead, you try to pass a series of statements, which is not supported by JavaScript. Check your browser console, it will probably show one or more syntax error messages.

To fix your code, you can move the statements before the append method call and pass the jQuery elements you are creating as an array, like this:

$(function(){
  $(".img-responsive").mousemove(function(e) {
    var alt = $(this).attr("alt");
    var src = $(this).attr("src");
    var newsrc = src.replace("small","medium");

    var preview= $('<div id="preview"></div>');
    var image = $('<img src="' + newsrc + '">');
    var caption = $('<p>' + alt + '</p>');
    $("main").append([preview, image, caption]);
  );
  });
});

Upvotes: 2

Related Questions