xRoisinDubh
xRoisinDubh

Reputation: 61

Moving an Image from one <div> to another <div> with CSS as part of a Javascript function

I'm a novice coder and I'm developing a simple card game as my first real project. I need help moving an img from one to another as part of a function that checks the score (if the score is over '99' it then runs the checkscore(); function. As part of this function, it appends the image from the 'trinkets-held' div, to the 'trinkets-lost' div. My problem is that I'm new to CSS animations and I'm trying to animate the move. Is my setup conducive to this or am I trying to tackle this all wrong?

Here is the html:

<body>
  <div id="trinkets-held-text">
    Trinkets Held
  </div>
  <div id="trinkets-held" style="text-align: center">
    <img alt="trinket1" id="trinket1" src="graphics/trinket1.png" style="width:100px;height:100px">
    <img alt="trinket2" id="trinket2" src="graphics/trinket2.png" style="width:100px;height:100px">
    <img alt="trinket3" id="trinket3" src="graphics/trinket3.png" style="width:100px;height:100px">
  </div>

  <br>

  <div id="trinkets-lost-text">
    Trinkets Lost
  </div>
  <div id="trinkets-lost" style="text-align: center"></div>
</body>

And here is the javascript functions needed to move the image:

function checkscore() {
    if (confirm("GAME OVER") === true) {
      document.getElementById('trinkets-lost').appendChild(document.getElementById('trinket1'));
      roundreset();
    }
    else {
      reset();
    }
}

How would I animate that move?

Upvotes: 2

Views: 7050

Answers (4)

Pascal Ockert
Pascal Ockert

Reputation: 984

Okay, here is another approach. It is a bit more complex, but it uses CSS3 transitions, a clone and a placeholder for centered positions and correct animations. Also, the original element is moved in the DOM, so your DOM actually represents the game's data model and the trinket is not only moved in an optical way.

You can test it in this fiddle.

HTML:

<div id="trinkets-held-text">
  Trinkets Held
</div>
<div id="trinkets-held" style="text-align: center">
  <img alt="trinket1" id="trinket1" src="http://upload.wikimedia.org/wikipedia/commons/thumb/1/13/Disc_Plain_red.svg/100px-Disc_Plain_red.svg.png" class="trinket">
  <img alt="trinket2" id="trinket2" src="http://upload.wikimedia.org/wikipedia/commons/thumb/0/07/Disc_Plain_green_dark.svg/100px-Disc_Plain_green_dark.svg.png" class="trinket">
  <img alt="trinket3" id="trinket3" src="http://upload.wikimedia.org/wikipedia/commons/thumb/0/02/Disc_Plain_blue.svg/100px-Disc_Plain_blue.svg.png" class="trinket">
</div>

<br>

<div id="trinkets-lost-text">
  Trinkets Lost
</div>
<div id="trinkets-lost" style="text-align: center"></div>

<input type="button" onclick="checkscore(1)" value="Check Score (red)">
<input type="button" onclick="checkscore(2)" value="Check Score (green)">
<input type="button" onclick="checkscore(3)" value="Check Score (blue)">

CSS:

.trinket, .trinket-placeholder {
    width: 100px;
    height: 100px;

    /* the animation */
    transition: all 1.5s;

    /* we need relative positions for the position transitions */
    position: relative;
}

.trinket-placeholder {
    display: inline-block;
    /* the negative margin adjusts the original trinket */
    margin-left: -100px;
    /* only keep transitions for the width, so we can remove the margin without transitions */
    transition: width 1.5s;
}

.trinket {
    top: 0;
    left: 0;
}

#trinkets-lost {
    /* add a height to the wrapper, so there is no flickering after moving the element */
    min-height: 110px
}

JS:

function checkscore(i) {
    if (confirm("GAME OVER") === true) {
        moveTrinket(i);
    } else {
        reset();
    }
}

function moveTrinket(i) {
    var trinketsLost = document.getElementById('trinkets-lost');
    var trinketsHeld = document.getElementById('trinkets-held');
    var trinketOrig = document.getElementById('trinket' + i);

    // clone the element (wee need the clone for positioning)
    var trinketClone = trinketOrig.cloneNode();
    trinketClone.style.visibility = 'hidden';
    trinketsLost.appendChild(trinketClone);

    // calculate the new position, relative to the current position
    var trinketOrigTop = trinketOrig.getBoundingClientRect().top;
    var trinketOrigLeft = trinketOrig.getBoundingClientRect().left;
    var trinketCloneTop = trinketClone.getBoundingClientRect().top;
    var trinketCloneLeft = trinketClone.getBoundingClientRect().left;
    var newPositionTop = (trinketCloneTop - trinketOrigTop);
    var newPositionLeft = (trinketCloneLeft - trinketOrigLeft);

    // remove the clone (we do not need it anymore)
    trinketClone.parentNode.removeChild(trinketClone);

    // create a placeholder to prevent other elements from changing their position
    var placeholder = document.createElement('div');
    placeholder.classList.add('trinket-placeholder');
    trinketOrig.parentNode.insertBefore(placeholder, trinketOrig.nextSibling);

    // position the original at the clone's position (this triggers the transition)
    trinketOrig.style.zIndex = 1000;
    trinketOrig.style.top = newPositionTop + 'px';
    trinketOrig.style.left = newPositionLeft + 'px';

    // this will be triggered after the transition finished
    trinketOrig.addEventListener('transitionend', function() {
        // reset the positioning
        this.style.position = 'scroll';
        this.style.top = 0;
        this.style.left = 0;

        // shrink the placeholder to re-center the held trinkets
        placeholder.style.width = 0;
        placeholder.style.marginLeft = 0;

        // when the placeholder transition has finished, remove the placeholder
        placeholder.addEventListener('transitionend', function (){
            this.parentnode.removeChild(this);

            // removing the placeholder is the last action,
            // after that you can do any following actions
            roundreset();
        });

        // move the trinket element in the DOM (from held to lost)
        trinketsLost.appendChild(this);
    });
}

Upvotes: 3

CodeGodie
CodeGodie

Reputation: 12132

Heres another approach with JQUERY and CSS

<!DOCTYPE html>

<html>
    <head>
        <title>Test</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <style>
            #trinkets-held, #trinkets-lost {
                height: 100px;
            }
            #trinkets-held img, #trinkets-lost img{
                width:100px;
                height:100px;
            }
            #trinkets-held img.move{
                -webkit-transition: 2s;
                -moz-transition: 2s;
                -ms-transition: 2s;
                -o-transition: 2s;
                transition: 2s;
                margin-top: 135px !important;
                position:absolute;
            }
        </style>
    </head>
    <body>
        <div id="trinkets-held-text">Trinkets Held</div>
        <div id="trinkets-held">
            <img alt="trinket1" id="trinket1" src="graphics/trinket1.png">
            <img alt="trinket2" id="trinket2" src="graphics/trinket2.png">
            <img alt="trinket3" id="trinket3" src="graphics/trinket3.png">
        </div>

        <br>

        <div id="trinkets-lost-text">Trinkets Lost</div>
        <div id="trinkets-lost">

        </div>



        <button id="doTheMove1" class="move_btns" value="trinket1">Score of Trinket1</button>
        <button id="doTheMove2" class="move_btns" value="trinket2">Score of Trinket2</button>
        <button id="doTheMove3" class="move_btns" value="trinket3">Score of Trinket3</button>


        <script>
            $(document).ready(function() {
                var score = 100;
                function checkscore(img_id) {
                    if (score > 99) {
                        $("#" + img_id).addClass("move"); //will slide it down

                        setTimeout(function() {//will wait for SECONDS then run function
                            $("#" + img_id).appendTo("#trinkets-lost");
                        }, 2000);//SECONDS
                    }
                }

                $(".move_btns").click(function() {
                    var img_id = $(this).val();
                    checkscore(img_id);
                });
            });
        </script>
    </body>

</html>

Upvotes: 0

CodeGodie
CodeGodie

Reputation: 12132

If you are limited to pure JavaScript, try this:

HTML:

<body>
    <div id="trinkets-held-text">
        Trinkets Held
    </div>
    <div id="trinkets-held" style="text-align: center">
        <div style="width:100px;height:100px; display: inline-block;">
            <img alt="trinket1" id="trinket1" src="graphics/trinket1.png" style="width:100px;height:100px">
        </div>
        <div style="width:100px;height:100px; display:inline-block;">
            <img alt="trinket2" id="trinket2" src="graphics/trinket2.png" style="width:100px;height:100px">
        </div>
        <div style="width:100px;height:100px; display:inline-block;">
            <img alt="trinket3" id="trinket3" src="graphics/trinket3.png" style="width:100px;height:100px">
        </div>


    </div>

    <br>

    <div id="trinkets-lost-text">
        Trinkets Lost
    </div>
    <div id="trinkets-lost" style="text-align: center"></div>



    <button onclick="checkscore('trinket1')">MOVE THE IMAGE</button>
    <button onclick="checkscore('trinket2')">MOVE THE IMAGE</button>
    <button onclick="checkscore('trinket3')">MOVE THE IMAGE</button>

</body>

JS:

<script>
        function checkscore(id) {
            var elem = document.getElementById(id);
            var style = "margin-top";
            var unit = "px";
            var from = 0;
            var to = 200;
            var time = 1000;

            elem.style['position'] = "absolute";
            elem.style['margin-left'] = "-50px";
            var start = new Date().getTime(),
                    timer = setInterval(function() {
                        var step = Math.min(1, (new Date().getTime() - start) / time);
                        var thestyle = (from + step * (to - from)) + unit;
                        elem.style[style] = thestyle;
                        if (step == 1)
                            clearInterval(timer);
                    }, 25);
            elem.style[style] = from + unit;
        }
    </script>

Heres a FIDDLE

Upvotes: 0

user3562712
user3562712

Reputation:

You could just run the animation that you want with a callback function that swaps the img src.

This example uses slideToggle to remove the image, swaps the src, and uses slideToggle again to make the image visible again:

HTML:

<img class="kittens" id="kittens-1" src="http://cdn.superbwallpapers.com/wallpapers/animals/kitten-16219-1280x800.jpg"></img>
<img class="kittens" id="kittens-2" src="http://critterbabies.com/wp-content/gallery/kittens/happy-kitten-kittens-5890512-1600-1200.jpg"></img><br/>
<input type="button" class="move" value="Move image" />


CSS:

.kittens {
    width: 300px;
    height: 300px;
}


Javascript:

$(function() {
    $('.move').click(function() {
        var img1 = $('#kittens-1').attr('src'),
            img2 = $('#kittens-2').attr('src');
        $('.kittens').slideToggle('slow', function() {
            $('#kittens-1').attr('src', img2);
            $('#kittens-2').attr('src', img1);
        }).slideToggle('slow');        
    });
});


Here is a fiddle

Upvotes: 0

Related Questions