I am trying to replace some text on my sites page using javascript. I must use javascript because the replacement is dependent on the site resolution. However I found that the code bellow doesn't work. Why is it? Does similar things work on iphone (these javascript functions)? Thanks.
<SCRIPT language="JavaScript">
<!--
if ((screen.width<=500))
{
document.body.innerHTML = document.body.innerHTML.replace('text to replace', 'replacement');
}
//-->
</SCRIPT>
-
by not work I mean that it doesn't replace anything.Brana– Brana2015年04月05日 02:03:56 +00:00Commented Apr 5, 2015 at 2:03
-
1That code is correct and will replace the first instance of 'text to replace' with 'replacement'. Maybe your issue is that the code is being executed before the page is fully loaded? Where are you placing this script block in your HTML file?bodagetta– bodagetta2015年04月05日 02:04:45 +00:00Commented Apr 5, 2015 at 2:04
-
in the middle of it. Where should i place it?Brana– Brana2015年04月05日 02:05:40 +00:00Commented Apr 5, 2015 at 2:05
-
1True, i added at the end of the page and now it works. thanks.Brana– Brana2015年04月05日 02:10:56 +00:00Commented Apr 5, 2015 at 2:10
-
1Glad you got it working! You can put it anywhere if you listen for an event that the DOM has been fully loaded: developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoadedbodagetta– bodagetta2015年04月05日 02:12:23 +00:00Commented Apr 5, 2015 at 2:12
3 Answers 3
The screen property does not have a resize cause it's like they built it in the factory :)
You're probably interested in window.innerWidth
probably you're also interested in listening for a resize event so here you go:
function doOnResize() {
var winW = window.innerWidth;
if(winW <= 500) {
document.body.innerHTML = document.body.innerHTML.replace('text to replace', 'replacement');
}
}
doOnResize(); // Do it as soon as you can
window.addEventListener("resize", doOnResize); // and on window resize
Also make sure to place the above <script> right before the closing </body> tag. This will make sure that the JS parser is in known about the DOM content before searching and replacing text.
6 Comments
window is the Browser's window object, which on desktop is usually smaller than screen logically, and on resize you can than catch the desired values. So yes, use window in any case.Your code does not work because it is executed before the DOM is ready.
window.onload = function() { /* Your code here */ };
This will make sure the DOM is ready and everything is loaded.
2 Comments
What about using css and js (well, jquery would probably be best) to change the display attribute of the element on the event that triggers the text change?