1

I'm trying to replace the contents of a div with other contents, both contents are JavaScript codes, however, when I press the button that calls the function, the whole page refreshes, and the new JavaScript in the function gets loaded onto the page (and looks corrupted too)

Here's my JavaScript function that I use

function refresh(){
alert("button pressed");
$("#tweet1").html('<script>new TWTR.Widget({version: 2,  type: "search",  search: "#abbaseya",  interval: 15000,  subject: "widget",  width: 300,  height: 360,theme: {    shell: {      background: "#8ec1da",      color: "#ffffff"    },tweets:{background:"#ffffff",color:"#444444",links:"#1985b5"}},features:{scrollbar:true,loop:true,live:true,behavior:"default"}}).render().start();<\/script>');
}

What am I doing wrong? tweet1 is just a div with an id, and the function above gets called by a button

here's the button I'm using, I have a form in the html

<form style="float:right; ">
        <input type="text"/><input type="button" value="Refresh" onclick="refresh()"/>
        </form>
3

1 Answer 1

3

There's really no reason to dynamically inject an inline script tag into a DOM element. Just execute the body of the script tag as regular JavaScript.

function refresh() {
  alert("button pressed");
  new TWTR.Widget({version: 2,  type: "search",  search: "#abbaseya",  interval: 15000,      
  subject: "widget",  width: 300,  height: 360,theme: {    shell: {      background:
   "#8ec1da",      color: "#ffffff"    },tweets:
  {background:"#ffffff",color:"#444444",links:"#1985b5"}},features:
  {scrollbar:true,loop:true,live:true,behavior:"default"}}).render().start();
  return false; // prevent refresh
}
Sign up to request clarification or add additional context in comments.

5 Comments

I tried your solution, the page still refreshes altogether and I'm presented only with that piece of javascript in the whole page.
It will still refresh if there's an error, as it will never get to "return false". So remove the "return false" and look for an error message (in Chrome devtools, firebug, whatever).
only in IE it shows an error within the twitter widget itself =( document.getElementsByTagName(...).0' is null or not an object
Different problem then. In that case, start a separate question with subject and tags about the twitter widget
I'm marking this as the answer since the code is ok, even though the problem turned out to be with the widget itself

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.