Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Mar 2012
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Dynamically changing .style attributes

    Hi All

    I have a piece of script which makes a div slide out from the side of the screen with information on it. I can change the innerHtml etc no problem, but i have a problem with change .style attributes dynamically. My code:

    Code:
    var mystring = "height:500px";
    var keyVal = mystring.split(":")
    var slidingDiv = document.getElementById('slidingDiv');
    slidingDiv.style.keyVal[0] = keyVal[1];
    As you see above i get a value which i need to split() to get the key and value to use. So what i would like to see is:

    slidingDiv.style.height = 500px;
    But it does not work, as there is no such function as slidingDiv.style.keyVal[0];
    How do i change this?

    I hope I've explained this thoroughly enough. Please ask if i need to explain further.

    Regards
    Marinus

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,396
    Thanks
    12
    Thanked 569 Times in 562 Posts
    There are three possible ways to set the style property with Javascript

    1.
    Code:
    element.style.propertyname = "value";
    2.
    Code:
    element.style["propertyname"] = "value";
    3.
    Code:
    element.style.cssText = "propertyname : value";
    Now you have to decide which one to take. As you already have a CSS string "height: 500px" you can choose the third option. If you want to stick to .split-ting the string into key/value pairs, you should use the second option
    Code:
    slidingDiv.style[keyVal[0]] = keyVal[1];

  • Users who have thanked devnull69 for this post:

    Mince (03-02-2012)

  • #3
    New to the CF scene
    Join Date
    Mar 2012
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Hi devnull69

    I used the code:

    Code:
    element.style["propertyname"] = "value";
    and it works perfectly, thanks so much for your help!


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •