tags:

views:

47

answers:

3

I am trying to echo out some JavaScript, but I can't get the formatting right I start off by putting the javascript I want to out into a string

$javascript = 'onmouseover="this.style.backgroundColor='blue'" onmouseout="this.style.backgroundColor='white'"';

and then echo it out like this

 $hint="<span $javascript>".$artistname->item(0)->childNodes->item(0)->nodeValue."</span>";

any help would be much appreciated

+1  A: 

As you can tell from the coloring in the quoted code, you need to escape your single quotes. You will end up with:

$javascript = 'onmouseover="this.style.backgroundColor=\'blue\'" onmouseout="this.style.backgroundColor=\'white\'"';
TNi
+4  A: 

Using the event attributes is considered bad practise. JavaScript should be unobtrusive. Also, I do not see why you would have to store the attributes in a PHP variable instead of simply adding them to the span tag directly. And last but not least, why dont you just use the CSS :hover selector to change the background color when the mouse is over the span? That would be a clean approach.

Gordon
+1  A: 

You should start with the output string. You want it to look like this:

onmouseover="this.style.backgroundColor='blue'"
onmouseout="this.style.backgroundColor='white'"

Now, in order to put that string in PHP into a variable, you need to surround it with either single or double quotes. Since your string contains both single and double quotes, either of them needs to be "escaped".

Using single quotes:

$javascript = 'onmouseover="this.style.backgroundColor=\'blue\'"
               onmouseout="this.style.backgroundColor=\'white\'"';

Using double quotes:

$javascript = "onmouseover=\"this.style.backgroundColor='blue'\"
               onmouseout=\"this.style.backgroundColor='white'\"";

Edit:

Final note: read carefully what Gordon has posted.

Anax