1

why does the following not work ?

javascript:

document.getElementById("page").style = "-webkit-filter: blur(5px);";

HTML:

<div id="page" style="" >some content</div>

Thanks

eds1999
  • 908
  • 2
  • 9
  • 25

2 Answers2

7

Make sure you call it after the element is ready, using something like window.onload or just having the script physically on the page after the element...and set the appropriate property:

window.onload = function () {
    document.getElementById("page").style.webkitFilter = "blur(5px)";
};

The style property of an element is an object with properties you need to set. You shouldn't and can't just set the style property as a string. I get a SyntaxError: invalid label error when I try to.

I understand it was probably confusing for setting the special "-webkit-filter" style, but the "-webkit-" styles follow a convention in the style object - no leading "-", and replace other "-"s with camelCase.

At the same time, it's probably easier and more efficient (so you can add other styles) to toggle a class, instead of specifically setting a style property. So I would suggest using:

document.getElementById("page").className += " transformer";

And defining the CSS class:

.transformer {
    -webkit-filter: blur(5px);
}

That way, if there are styles implemented in other specific browsers, it's easy to just add them here. Specifically, the use of vendor prefixes.

Ian
  • 48,619
  • 13
  • 99
  • 109
0

You're probably executing the script before the element was added to the page.

If your page is along the lines of:

<!DOCTYPE html>
<html>
<head>
    <script>...</script>
</head>
<body>
    <div id="page">some content</div>
</body>
</html>

Then you'll need to wait for the document to be ready or the onload event before trying to access the #page element.

zzzzBov
  • 167,057
  • 51
  • 314
  • 358