dave
dave

Reputation: 481

How to move an image element using javascript and how to make it stay there

using javascript i want to click on a link, and then have javascript move an image element to some location. Only problem im facing is that the image element won't stay there, why is that

sample javascript:

function move( e )
{  
    var clickedLink = e.target;    
    // getting location of clicked link.
    clickedLink.style.left = "200px";
    clickedLink.style.top = "200px";
}

css for the "clickedLink" element object in the function move above.

#clickedLink 
{
  left: 0px;  
  position: relative;
  top: -500px;
  z-index: 10;   
}

Upvotes: 1

Views: 3295

Answers (4)

Anand Thangappan
Anand Thangappan

Reputation: 3106

Target don't have a style option just change into e.

 function move( e )
{  
    var clickedLink = e.target;    
    // getting location of clicked link.
    e.style.top = "200px";
    e.style.left = "200px";

}

Upvotes: 1

Yevgeny Simkin
Yevgeny Simkin

Reputation: 28349

if you want it to persist in place after the page has refreshed, you'll need to store its location in a cookie and load it when the page loads.

Upvotes: 0

Ben
Ben

Reputation: 57217

The changes made using Javascript will not persist over a page reload.

A permanent change must be made using the CSS, otherwise the element must be re-moved using Javascript every time the page is loaded.

You could save the client's preferences in a cookie, for example, then use the window.onload event to fire a function that checks the cookie, and updates the element accordingly.

Or, you could use a server-side script that generates an extra CSS file customized to fit the current user's preferences (assuming it's the same user) when they save. Then, check for this file's existence when the page is loaded (again with server-side script).

The main point is, Javascript changes are only temporary since they happen one time on the client's browser.

Upvotes: 0

Paul
Paul

Reputation: 36319

When you say it won't "stay there", you aren't trying to get it to stay there after the page refreshes w/o saving it's new location somewhere, are you?

UPDATE: To store the location, it depends on why you're storing it. You can store it in a cookie as others have suggested, but that will only save it for that one user, in that one browser, and only until they clear the cookies.

If you want to make a change that stays w/ the user across different browsers, or make it available to other users... then you'll need to persist the change to a server via Ajax and you'll have to have the server-side code load in the location settings, etc.

Upvotes: 0

Related Questions