简体   繁体   中英

jQuery function to open 2 connected, draggable images on click

I am new to programming and it should be easy, however I can't understand how to do it. I need create 2 images on one button click, one image is main, another is like close X button. They must be connected and draggable.

This is my function: Js Fiddle link

<input type="button" id="truck" class="truckbtn" value="ADD Truck" onclick="addtruck()">
<div id="masina">
    <div id="closebutton"></div>
    <div id="truckshow"></div>
</div>

<Script>
    $(document).ready(function() {
        $(".truckbtn").click(function() {
            var truckshow = $('<img height="200" width="100" src="images/Truck1.png">');
            var closebutton = $('<img height="50" width="50" src="images/closeimage2.png">');
            $('div').prepend(truckshow + closebutton);
            truckshow.draggable();
            closebutton.draggable();
        });
    });
</Script> 

Here I have a sample code ( JS Fiddle ) using draggable() of Jquery UI for dragging components inside DOM. My buttons style are from Bootstrap , you can also write custom CSS although I used a framework for saving time.

EDITS

Image is dynamically added on button click. You can change image dynamically by changing src of <img/> tag using jquery. let <img id="myImage"/> then you can set src by $("#myImage").attr("src","your link here"); .

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM