How do I change innerHTML of loaded page with JQuery - javascript

I want my jquery to change text inside blocks with class "ToChange". It works fine inside current html file, but it does not with external html file (that I insert with "load" method). Here is my code:
index.html :
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home page</title>
<script src="jquery-3.1.1.js"></script>
<script>
$(function(){
$('.insert_external').load("external.html");
});
</script>
<script>
$(function(){
length = document.getElementsByClassName("ToChange").length;
for (i = 0; i < length; i++) {
document.getElementsByClassName("ToChange")[i].innerHTML = "New Text";
}
});
</script>
</head>
<body>
<div class="insert_external"></div>
<div class="ToChange">
This changes fine
</div>
<div class="ToChange">
This changes fine too
</div>
</body>
</html>
external.html :
<div class="ToChange">
This text does not change :(
</div>
As result I see 3 strings :
This text does not change :(
New Text
New Text
And I want all of them to be "New Text". Is it possible to do so using only html and js with jquery?

You have to change the html inside load() callback so the new data is here, else it will change in the old DOM since the JS works asynchronously.
You've to wait for the .load() to finish the request :
$('.insert_external').load("external.html", function() {
length = document.getElementsByClassName("ToChange").length;
for (i = 0; i < length; i++) {
document.getElementsByClassName("ToChange")[i].innerHTML = "New Text";
}
});
NOTE : Since you're using jQuery it'll be better to use .each() function instead :
$('.insert_external').load("external.html", function() {
$(".ToChange").each(function(){
$(this).text("New Text");
})
})
Hope this helps.

The function updating the text is running before the new content is actually loaded, because the load-function works asynchronously. You should wait until the new data has loaded. For this, use the callback of the .load()-function.

Try something like that
<script>
$(function(){
$('.insert_external').load("external.html",function(){
setText();
});
});
</script>
<script>
$(function(){
function setText(){
length = document.getElementsByClassName("ToChange").length;
for (i = 0; i < length; i++) {
document.getElementsByClassName("ToChange")[i].innerHTML = "New Text";
}
}
});
</script>
You just have to set a callback function when completed.

Related

Text appearing with delay

I'm trying to find the solution that how can i make a text appear on the page after 10 seconds of page load? example text..
I didn't do anything, because I think it's about javascript here...
Example : Something like this: http://postimg.org/image/duogy83zd/
Try below code, thats what you need :
<html>
<head>
<script>
window.onload = function(){
var theDelay = 10;
var timer = setTimeout("showText()",theDelay*1000)
}
function showText(){
document.getElementById("delayedText").style.visibility = "visible";
}
</script>
</head>
<body>
<div id="delayedText" style="visibility:hidden">
I didn't do anything, because I think it's about javascript here...
</div>
</body>
</html>

javascript code in html to js file

I am struggling with the following problem.
I have made a memorygame with javascrpt for school.It all works fine, but my teacher told me that i can not have on line of javascript in my HTML, like this :
HTML :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="styles.css">
<title>Memory spelen</title>
</head>
<body>
<script type="text/javascript" src="javascript.js"></script>
<div id="memory_board"></div>
<script>newBoard();</script>
</body>
</html>
The newBoard() is applied to the memory_board div. How can i take this little piece of script out of my HTML file and place it in my js file, to still function properly.
Thanks in advance
Inside of your javascript.js put this
window.onload = function {
// content of your script
var newBoard = function(){
// the new updated newBoard() function from below
}
// other parts of your script
if(window.location.href == 'your-url') {
// now, after the newBoard() has been updated
// the next to lines are not needed
// var board = document.getElementById('memory_board');
// board.innerHTML = newBoard();
// just call the function
newBoard();
}
};
UPDATE
I just took a look at your old fiddle and I changed your newBoard function to this
function newBoard(){
tiles_flipped = 0;
var output = '';
memory_array.memory_tile_shuffle();
for(var i = 0; i < memory_array.length; i++){
var div = document.createElement('DIV');
div.id = "tile_" + i;
(function(div,i){
div.onclick = function() {
memoryFlipTile(this, memory_array[i]);
};
}(div,i));
document.getElementById('memory_board').appendChild(div);
}
}
Check the working fiddle.
try to put it like this in external js file
$(document).ready(function(){
newBoard();
});
It looks that you need to call newBoard() method on onload event of memory_board div , You can do this in following ways:
<div id="memory_board" onload="javascript:newBoard()" ></div> // use onload event of memory_board
you can use onload function on the javascript. It will call the function when all the HTML tag is loaded on the screen.

javascript addEventListener is not working

I'm writing a simple chrome extension that lists all the open tabs, I have this code on it
function changeTab(tabID){
chrome.tabs.update(tabID,{active:false})
}
chrome.windows.getCurrent({populate: true},function (window){
list = document.getElementById('open-tabs');
for (var i = 0; i < window.tabs.length; i++)
{
var li = document.createElement('li');
var element = document.createElement('a');
element.setAttribute('href','#');
element.innerHTML = window.tabs[i].title;
element.addEventListener("click",function(){
changeTab(window.tabs[i].id);
},false);
li.appendChild(element);
list.appendChild(li);
}
});
It lists the open tabs, but doesn't seem to add the onClick event, when I checked the chrome console I get this
Why is not adding the event correctly?
--edit--
Adding the html if it helps
<!doctype html>
<html>
<head>
<title>Count Me</title>
<link rel="stylesheet" href="popup.css" type="text/css">
<script src="popup.js"></script>
</head>
<body>
<div id="main">
<ul id="open-tabs"></ul>
</div>
</body>
</html>
Edit2
I tried using the sugestion given on an answer using the .bind(this,i) but still doesn't work, I added console.log() to see what's happening, and it seems it's not going inside the addEventListener heres the code with the log calls:
function changeTab(tabID){
chrome.tabs.update(tabID,{active:false})
}
chrome.windows.getCurrent({populate: true},function (window){
list = document.getElementById('open-tabs');
for (var i = 0; i < window.tabs.length; i++)
{
var li = document.createElement('li');
var element = document.createElement('a');
element.setAttribute('href','#');
element.innerHTML = window.tabs[i].title;
console.log('before');
console.log(window.tabs[i].id);
element.addEventListener("click",function(iVal){
console.log('inside');
changeTab(window.tabs[iVal].id);
}.bind(this,i),false);
console.log('after');
console.log(window.tabs[i].id);
li.appendChild(element);
list.appendChild(li);
}
});
As you can see I have a Before and After console.log() as well as inside the addEventListener and it doesn't seem to call anything inside the addEventListener as you can see here:
It's calling the console.log inside the addEventListener but still isn't working
Try adding a closure around the function
(function(num) {
element.addEventListener("click",function(){
changeTab(window.tabs[num].id);
},false);
})(i)
The event will be executed a later stage when you click the element. So when the for loop is completed, i always points to last iterated value.
So enclosing it in an anonymous function creates a closure around the variable which will be available at the time the click event occurs.
Your function callback is happening in a context that does not recognize i..
You can bind the i value to function and by that make it work:
element.addEventListener("click",function(iVal){
changeTab(window.tabs[iVal].id);
}.bind(this,i),false);

"getElementsByTagName(...)[0]" is undefined?

I have the following code, which basically toggles through a bunch of images.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var num = 1;
img = document.getElementsByTagName("img")[0];
hbutton = document.getElementsByTagName("h1")[0];
hbutton.onclick = function() {
num += 1;
img.src = num + ".jpg";
}
</script>
</head>
<body>
<h1>Press Here!</h1>
<img src = "1.jpg"></img>
</body>
</html>
For some reason, when I run it, nothing happens, because of the following error as displayed by my Firebug console.
hbutton is undefined
---
hbutton.onclick = function() {
When I run just the JS after the page has loaded however, it works perfectly fine!!! Why is this?
Your code is executing before the h1 tag is defined. You must run it in an onload handler or put it just before /body
JavaScript is interpreted top-to-bottom. So at the place where your <script> executes, no h1 tags are known yet.
Try putting the <script>-Tag to the bottom of your page. Otherwise, if you need the script at the beginning of the page, an onLoad-Handler might help:
<script type="text/javascript">
function onLoadHandler() {
// your original javascript code here...
}
</script>
<body onload="onloadHandler()">
<!-- HTML Code here-->
When you put it in the header, your h1 is not loaded yet. hbutton becomes undefined, not an object. Then when you try to set .onclick, it breaks because you cant set properties of something undefined. When you put the code in the body, your h1 is already loaded, so the code works as you expected it to.
You can fix this by leaving your code at the top, but only calling it after an onload event.
The head gets executed before the dom is loaded. Put it on the button of the page or put an onload function in the body tag.
It cannot find document.getElementsByTagName("img") when the Document isnt ready yet, because it is simply not there yet.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function onDocumentReady(){
var num = 1;
img = document.getElementsByTagName("img")[0];
hbutton = document.getElementsByTagName("h1")[0];
hbutton.onclick = function() {
num += 1;
img.src = num + ".jpg";
}
}
</script>
</head>
<body onload="onDocumentReady()">
<h1>Press Here!</h1>
<img src = "1.jpg"></img>
</body>
</html>
or simply do this:
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Press Here!</h1>
<img src = "1.jpg"></img>
<script type="text/javascript">
var num = 1;
img = document.getElementsByTagName("img")[0];
hbutton = document.getElementsByTagName("h1")[0];
hbutton.onclick = function() {
num += 1;
img.src = num + ".jpg";
}
</script>
</body>
</html>
The problem is that the script is being executed immediately it is encountered during page load.
Since it's at the top of the page, in the header, this means that it is executed before the page has loaded the <h1> element (or any of the rest of the body).
Therefore, when it asks for getElementsByTagName('h1'), there aren't any matching elements at that moment in time.
You need to either:
* move the code to the end of the script.
* or wrap it in a function, and trigger the function to execute when the page has finished loading -- ie use the onload method.

How do you execute a dynamically loaded JavaScript block?

I'm working on a web page where I'm making an AJAX call that returns a chunk of HTML like:
<div>
<!-- some html -->
<script type="text/javascript">
/** some javascript */
</script>
</div>
I'm inserting the whole thing into the DOM, but the JavaScript isn't being run. Is there a way to run it?
Some details: I can't control what's in the script block (so I can't change it to a function that could be called), I just need the whole block to be executed. I can't call eval on the response because the JavaScript is within a larger block of HTML. I could do some kind of regex to separate out the JavaScript and then call eval on it, but that's pretty yucky. Anyone know a better way?
Script added by setting the innerHTML property of an element doesn't get executed. Try creating a new div, setting its innerHTML, then adding this new div to the DOM. For example:
<html>
<head>
<script type='text/javascript'>
function addScript()
{
var str = "<script>alert('i am here');<\/script>";
var newdiv = document.createElement('div');
newdiv.innerHTML = str;
document.getElementById('target').appendChild(newdiv);
}
</script>
</head>
<body>
<input type="button" value="add script" onclick="addScript()"/>
<div>hello world</div>
<div id="target"></div>
</body>
</html>
You don't have to use regex if you are using the response to fill a div or something. You can use getElementsByTagName.
div.innerHTML = response;
var scripts = div.getElementsByTagName('script');
for (var ix = 0; ix < scripts.length; ix++) {
eval(scripts[ix].text);
}
While the accepted answer from #Ed. does not work on current versions of Firefox, Google Chrome or Safari browsers I managed to adept his example in order to invoke dynamically added scripts.
The necessary changes are only in the way scripts are added to DOM. Instead of adding it as innerHTML the trick was to create a new script element and add the actual script content as innerHTML to the created element and then append the script element to the actual target.
<html>
<head>
<script type='text/javascript'>
function addScript()
{
var newdiv = document.createElement('div');
var p = document.createElement('p');
p.innerHTML = "Dynamically added text";
newdiv.appendChild(p);
var script = document.createElement('script');
script.innerHTML = "alert('i am here');";
newdiv.appendChild(script);
document.getElementById('target').appendChild(newdiv);
}
</script>
</head>
<body>
<input type="button" value="add script" onclick="addScript()"/>
<div>hello world</div>
<div id="target"></div>
</body>
</html>
This works for me on Firefox 42, Google Chrome 48 and Safari 9.0.3
An alternative is to not just dump the return from the Ajax call into the DOM using InnerHTML.
You can insert each node dynamically, and then the script will run.
Otherwise, the browser just assumes you are inserting a text node, and ignores the scripts.
Using Eval is rather evil, because it requires another instance of the Javascript VM to be fired up and JIT the passed string.
The best method would probably be to identify and eval the contents of the script block directly via the DOM.
I would be careful though.. if you are implementing this to overcome a limitation of some off site call you are opening up a security hole.
Whatever you implement could be exploited for XSS.
You can use one of the popular Ajax libraries that do this for you natively. I like Prototype. You can just add evalScripts:true as part of your Ajax call and it happens automagically.
For those who like to live dangerously:
// This is the HTML with script element(s) we want to inject
var newHtml = '<b>After!</b>\r\n<' +
'script>\r\nchangeColorEverySecond();\r\n</' +
'script>';
// Here, we separate the script tags from the non-script HTML
var parts = separateScriptElementsFromHtml(newHtml);
function separateScriptElementsFromHtml(fullHtmlString) {
var inner = [], outer = [], m;
while (m = /<script>([^<]*)<\/script>/gi.exec(fullHtmlString)) {
outer.push(fullHtmlString.substr(0, m.index));
inner.push(m[1]);
fullHtmlString = fullHtmlString.substr(m.index + m[0].length);
}
outer.push(fullHtmlString);
return {
html: outer.join('\r\n'),
js: inner.join('\r\n')
};
}
// In 2 seconds, inject the new HTML, and run the JS
setTimeout(function(){
document.getElementsByTagName('P')[0].innerHTML = parts.html;
eval(parts.js);
}, 2000);
// This is the function inside the script tag
function changeColorEverySecond() {
document.getElementsByTagName('p')[0].style.color = getRandomColor();
setTimeout(changeColorEverySecond, 1000);
}
// Here is a fun fun function copied from:
// https://stackoverflow.com/a/1484514/2413712
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
<p>Before</p>

Categories