Jonathon
Jonathon

Reputation: 2699

Inserted code producing unexpected result

So eventually I want to have a greasemonkey script but for now I have only been working with firebug to test out my html/javascript.

I have this code to insert one button in the HTML toolbar for blogger. The button is supposed to replace all the   with " " as blogger seems to just randomly add   into my blogs posts and can cause the published article to look weird (a bunch of words separated in between with  s will not want to break in the middle unlike the same words separated with " ").

 document.getElementById("postingHtmlToolbar").firstChild.innerHTML += '<div id="SP" class="goog-inline-block goog-toolbar-button" title="SP" role="button" style="-moz-user-select: none;"><div class="goog-inline-block goog-toolbar-button-outer-box"><div class="goog-inline-block goog-toolbar-button-inner-box"><a href="javascript:document.getElementById(\'postingHtmlBox\').value = document.getElementById(\'postingHtmlBox\').value.replace(/&nbsp;/g, \' \');"><b>SP</b></a></div></div></div>';

Which trimming away the formatting just leaves us with.

  <a href="javascript:document.getElementById('postingHtmlBox').value = document.getElementById('postingHtmlBox').value.replace(/&nbsp;/g, ' ');"><b>SP</b></a>

The funny thing is that that same code (minus the href, javascript: stuff) run from firebug works perfectly.

But when it is inserted like this and run it blanks the entire web page and writes the value of document.getElementById('postingHtmlBox').value.replace(/&nbsp;/g, ' ') into this black page.

Am I forgetting something stupid? Is this supposed to happen? Do I have some stupid syntax error? What would you suggest as a solution?

Upvotes: 0

Views: 97

Answers (2)

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114367

Don't put JS code in href. use onclick:

<a href="javascript//" onclick="document.getElementById('postingHtmlBox').value = document.getElementById('postingHtmlBox').value.replace(/&nbsp;/g, ' ');"><b>SP</b></a>

Upvotes: 1

hair raisin
hair raisin

Reputation: 2628

Try adding void(0); to the end of the href.

Basically, the output of the last statement (if any) is replacing the document (i've had the same problem), so making the last statement one with no output will avoid the problem

Upvotes: 1

Related Questions