Local variable problem inside event in javascript
I am shooting a page that has a large and draggable div. I have attached mousedown, mousemove and mouseup event handlers to this div.
The problem is with the mousemove event handler. I have to get the current width, height, top and left of the div. For this, I use functions to return specific values, and I have to use those values โโin different conditions inside the main function.
If I try to assign local variables with these values โโand use those variables in the previous code, then the script becomes slow. This means you can resize and drag.
But if I call the functions every time instead of using these variables in the condition, then there is no delay.
What will be the cause of this problem?
Sample code
// Code executes with a delay
function AdjustElement()
{
var elemHeight = GetHeight ( elem );
var elemWidth = GetWidth ( elem );
var elemTop = GetTop ( elem );
var elemLeft = GetLeft ( elem );
if ( elemLeft >= 20 && elemRight <= 200 )
{
//code for moving element
}
if ( elemTop >= 20 && elemTop <= 200 )
{
// code for moving element
}
if ( elemHeight >= 60 && elemHeight <= 300 )
{
// code for resizing element
}
if ( elemWidth >= 60 && elemWidth <= 300 )
{
// code for resizing element
}
}
// Code executes without delay
function AdjustElement()
{
if ( GetLeft(elem) >= 20 && GetRight(elem) <= 200 )
{
//code for moving element
}
if ( GetTop(elem) >= 20 && GetTop(elem) <= 200 )
{
// code for moving element
}
if ( GetHeight(elem) >= 60 && GetHeight(elem) <= 300 )
{
// code for resizing element
}
if ( GetWidth(elem) >= 60 && GetWidth(elem) <= 300 )
{
// code for resizing element
}
}
// General functions
function GetWidth(elem)
{
return elem.offsetWidth;
}
function GetHeight(elem)
{
return elem.offsetHeight;
}
function GetTop(elem)
{
return elem.offsetTop;
}
function GetLeft(elem)
{
return elem.offsetLeft;
}
source to share
No one has answered this question yet
Check out similar questions: