0

Sorry couldn't think of a better title. :)

Here goes,

I have been pulling my hair out for hours trying to figure this out.

I have the following function:

function changeCss(elem, styles) {

   var oldstyles = styles;

   elem.css( styles )

   for(var key in styles){
       var oldstyle = input.css(key);
     oldstyles[key] = oldstyle;              //this line is the issue
       elem.data( 'oldstyle', oldstyles )                      
   }
}

Here is an example of how it gets called:

var theStyle = { border: '1px solid red'};
//elem is a jQuery object of an HTML element

changeCss(elem, thestyle);

The problem is that after the commented line ( line 8 ), styles's value is whatever oldstyles's value is.

So for example if that particular element's CSS attribute for border was not set, ie undefined, styles's value will be { border: "" }

How is that even possible? That is why I am delcaring oldstyles; I'm making a "backup" of the styles variable.

I have changed the 3rd line with var oldstyles = {}; and it seems to work correctly.

But this isn't how it is supposed to be, I need to have the old styles because later I want to reset the styles - but only the ones I changed.

I can't understand why it "breaks" when oldstyles equals styles?

I hope I am giving enough code for you to understand, and also that I am expaining myself good enough. :)

If anything is unclear, please ask.

Thank you for any insight and help.

2 Answers 2

1

It's because oldstyles is actually just a reference to styles rather than a copy. As it appears that you are using jQuery you can use the jQuery.extend to make oldstyles a copy of styles:

var oldstyles = {};
jQuery.extend(oldstyles, styles);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for your help and quick response! :) I'm giving you the check since you were first.
1

Javascript objects are passed by reference. That means that, in the line var oldstyles = styles;. you're creating a new variable that references the same value as styles.

In order to create a duplicate, you need to do this:

var oldstyles = {};
for (var style in oldstyles) {
  if (oldstyles.hasOwnProperty(style)) {
    oldstyles[style] = styles[style];
  }
}

In jQuery, you can just use $.extend():

var oldstyles = $.extend({}, styles);

1 Comment

Thank you very much for your help and responding so quickly :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.