E
E
Egor S2015-10-03 23:36:30
JavaScript
Egor S, 2015-10-03 23:36:30

Why is the value of marginLeft not changing?

(function () {
    var grab = false;
    var slides = null;
    onload = function () {
        init();
    };

    function init() {
        var rootEl = document.getElementsByClassName('containerBand');
        if (rootEl) {
            var root = rootEl[0];
            root.onmousemove = moveMouse;
            slides = root.getElementsByClassName('container');
            if (slides.length > 0) {
                for (var i = 0; i < slides.length; i++) {
                    slides[i].onmousedown = mouseClick;
                    slides[i].onmouseup = mouseUp;
                }
            }
        }
        else {
            return false;
        }
    };

    function moveMouse(e) {
        for (var i = 0; i < slides.length; i++) {
            var slide = slides[i];
            slide.style.marginLeft = slide.style.marginLeft + "20px";
        }
    };

    function mouseClick(e) {
        grab = true;
        return false;
    }

    function mouseUp() {
        grab = false;
    }
})();

Why, when onmousemove is triggered, changing the indentation in the line does not work
slide.style.marginLeft = slide.style.marginLeft + "20px";

Only works on the first onmousemove.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis, 2015-10-03
@mortyyyy

The answer is: " Because that's how the script is written " - when moving the mouse, set the "margin-left" property to "20px". Do not change this value with each movement according to some algorithm, but simply set it statically and that's it. It would be nice to know what result you expect?
OK, I won't torture you... In the loop where you are trying to change the value, print "slide.style.marginLeft" to the console. There are two options for what you'll see on the first fire: either an empty string, or an already set value that was written in the style attribute , for example, "30px". If the string is empty, then "" + "20px" == "20px" , if the value is, then "30px". In the latter case, at least modern browsers will ignore the invalid value. Solution: either pre-set some value in the style attribute of these elements, or in the loop where you set the onmousedown and onmouseup event handlers, add such a value, for example, slides[i].style.marginLeft = 0; , or use the getComputedStyle() method when you need to pick up the values ​​specified in CSS and do not forget to convert the received current value to a numeric type

slide.style.marginLeft = (parseInt(slide.style.marginLeft, 10) + 20) + "px";

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question