Search code examples
javascriptjqueryhtmlcssonmouseover

JQuery Select one of multiple img in div


I'm new to JQuery and stuck on a simple problem. I wanted to take the markup below, and create a script that places a larger version of the mouse'd over img (one of the five from div) into p, "big". The one in "big" will match the last mouseover target, and will function as a link- just the same as the smaller version.

<!doctype html>
    <html>
        <head>
            <meta charset = "UTF-8"/>
            <title>Image Links</title>
        </head>
        <body>
            <p id = "big">

            </p>
            <div id = "links">
                <a href = "http://www. .com/"><img id = " " border = "0" alt = " " src=" .png" width = "100" height = "150" onmouseover="enlargeCopy();">
                <a href = "https://www. .com "><img id = " " border = "0" alt = " " src=" " width = "200" height = "100">
                <a href = "https://www. .com/"><img id = " " border = "0" alt = " " src=" .png" width = "100" height = "100">
                <a href = "http://www. .com/"><img id = " " border = "0" alt = " " src=" .png" width = "100" height = "100">
                <a href = "https://www. .com/"><img id = " " border = "0" alt = " " src=" .png" width = "100" height = "100">
            </div>
            <script src="jquery-3.1.0.js"></script>
            <script src = "Test 3.js"></script>

        </body>
    </html>

This is the js script I've attempted to use ><. The closest I've come to success is getting [object Object] to appear multiple times (instead of the intended larger image).

//intended to increase the size of imgs in div, and place the larger image at the top of the document

var enlargeCopy = function () {

    var x = $(".links").children("img").css("width", "*=2");
    var x = $(".links").children("img").css("height", "*=2");

    document.getElementById("big").appendChild(document.createTextNode(x));
};

What I am attempting to do- explained more concisely:

-1. is to hover over any one of the five image anchors (in div of the html document)

-2. for the image that is being moused over to appear as a copy at the top of the page (in the currently empty p slot)

-3. for that copy to be twice as wide and twice as long as the moused over target

-4. for the copy to still also function as a link


Solution

  • If I understood you corectly you want to clone the image and append it to some element on mouseover, right? Maybe you can use jQuery's clone method:

    $('#links a').on('mouseover', function(){
      $(this).clone().appendTo('#big');
      var originalWidth = $(this).find('img').width();
      var originalHeight = $(this).find('img').height();
      $('#big, #big img').css({'width': originalWidth * 2 + 'px', 'height': originalHeight * 2 + 'px'});
    });
    Also, you should close your anchor tags like this </a>.

    I've also made you a FIDDLE.