Sami
Sami

Reputation: 477

Weird result of adding up two variables

I am trying to design a slider. Here is the codes. Check out the output of the top variable in the console log. Why is it an object and not a value?!. http://jsfiddle.net/YtTFb/

<div class="filter_opt_slider">
     <div></div>
</div>  

-

.filter_opt_slider{
    position: relative;
    width: 3px;
    margin:10px;
    height: 150px;
    border: 1px #E0E0E0 solid;
    background: #FFF;
    cursor: default;
}

-

$(document).ready(function(){

$(".filter_opt_slider div").on("mousedown",function(event){
    dragged=$(this);
    minY=parseInt(dragged.parent().offset().top);
    maxY=parseInt(dragged.parent().css("height"))+minY;
   $(document).mousemove(function(event) {

        if(event.pageY<=maxY && event.pageY>=minY){
            top=event.pageY-minY;

            console.log("minY: "+minY);
            console.log("pageY: "+event.pageY);
            console.log("top: "+top);
            console.log("<------------->")

            dragged.css({top:top})                
        }

    });
   $(document).on("mouseup",function(){
        $(document).unbind("mousemove")
        .unbind("mouseup");
   })
})

})

Upvotes: 0

Views: 57

Answers (3)

edi9999
edi9999

Reputation: 20574

It's because top is already declared as a property of window (by default , as @R-P mentions it)

To declare a variable inside a function, use the keyword var:

var top=event.pageY-minY;

top will be declared inside the scope of the function so they will not be any conflicts.

Update JSFIDDLE: http://jsfiddle.net/edi9999/YtTFb/2/

Upvotes: 0

R.P
R.P

Reputation: 500

The top property returns the topmost browser window of the current window. That's why it returns object: http://www.w3schools.com/jsref/prop_win_top.asp

Basically you haven't declared any of your variables: minY, maxY and top.

So add var in front of them or declare them before ready function.

Upvotes: 0

James Donnelly
James Donnelly

Reputation: 128796

It's because top is a pre-existing object. You're not using the var keyword to declare it, so you're simply assigning the value to the existing object.

Change:

top=event.pageY-minY;

To:

var top=event.pageY-minY;

http://jsfiddle.net/YtTFb/1/

Upvotes: 1

Related Questions