Home > Mobile >  Images wont move based on changes with vanilla javascript
Images wont move based on changes with vanilla javascript

Time:10-07

I am expecting the images to shift to the right. Runner increments and prints 1px, 2px, 3px ect. to console, but new margin wont be set. What's the problem?

What I have written above together with the code below should be sufficient to understand my problem, but I am at this point simply writing to get rid of the prompt to write more text.

<body>
    <div class="normal">
        <img id="normal" src="whiteboard.jpeg">
    </div>
    <div class="scaled">
        <img id="scaled" src="whiteboard.jpeg">
    </div>
</body>
<style>
    .normal{
        background-image: url('whiteboard.jpeg');
        position:absolute;
        z-index:-1;
    }
    .scaled{
        transform:scale(120%);
        z-index:2;
        clip-path: circle(5% at 33% 42%);
    }

    .normal, .scaled{
        width:100vw;
        
    }

    div img{
        width:100%;
        height:auto;
        
    }
</style>
<script>

    window.onload=function(){
        const normal = document.getElementById('normal');
        const scaled = document.getElementById('scaled');
        let runner =0;
        setInterval(function(){
            normal.style.marginRight="-" runner "px";
            scaled.style.marginRight="-" runner "px";
            runner  ;
            console.log("respons - " runner "px")
        },50);
        
    }

</script>

CodePudding user response:

The marginRight style describes the distance of the div element to its parent's right side. A negative marginRight will not work here - instead try marginLeft. Depending your desired direction of the animation use a positive or negative value.

window.onload = function() {
    const normal = document.getElementById('normal');
    const scaled = document.getElementById('scaled');
    let runner = 0;
    setInterval(function() {
        normal.style.marginLeft = "-"  runner   "px";
        scaled.style.marginLeft = "-"  runner   "px";
        runner  ;
        console.log("respons - " runner "px")
    }, 50);
}
<body>
    <div class="normal">
        <img id="normal" src="whiteboard.jpeg">
    </div>
    <div class="scaled">
        <img id="scaled" src="whiteboard.jpeg">
    </div>
</body>
<style>
    .normal {
        background-image: url('whiteboard.jpeg');
        position: absolute;
        z-index: -1;
        background-color: blue;
    }
    .scaled{
        transform: scale(120%);
        z-index:2;
        clip-path: circle(5% at 33% 42%);
        background-color: red;
    }

    .normal, .scaled{
        width: 100vw;
        
    }

    div img {
        width: 100%;
        height: auto;
        
    }
</style>

  • Related