Manipulating HTML in Javascript - javascript

I am trying to manipulate the text that is already inside the div and replace it with another strings from JavaScript, creating a basic animating effect by replacing particular character from strings present inside the div element, more precisely position based replacement of string. However when I wrote down the following code it doesn't work. What I wanted to do is that store the original text in one variable and when the dom replacement of text occurs then setting certain interval replace by the old text and again replace by the new randomize text creating text replacement animation in certain position of the text.
code :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var all ="ABCDEFGHIJKLMNOPQRSTUVWXYZa{}[];:></?bcdefghijklmnopqrstuvwxyz0123+_)(*&^%$##!~`456789";
var old_text = document.getElementById("text").innerText;
function randChar() {
"use strict";
return all.charAt(Math.floor(Math.random()*all.length));
}
function main() {
"use strict";
var $_inter = setInterval(function() {
var text = document.getElementById("text");
text.innerHTML = text.innerHTML.substring(0, 5) + randChar() + text.innerHTML.substring(5);
setTimeout(function(){
text.innerHTML = old_text;
},200);
}, 350);
}
window.onload = main;
</script>
</head>
<body>
<div id="text">Hello World!</div>
</body>
</html>
So in order to make it work for a while I used the original string as
setTimeout(function(){
text.innerHTML = "Hello World!";
},200);
Which is not possible as the text in page might have been generated dynamically. When I did run the first code it says innerText of Null.
The exact error it throws is:
Uncaught TypeError: Cannot read property 'innerText' of null
What does that mean, because text and element is there why can't it grab the text from dom?

Cannot read property 'innerText' of null
Your problem is being cause because you're getting #text before it is defined.
var old_text = document.getElementById("text").innerText;
You should include this in your window.onload function as it will exist then.
Uncaught ReferenceError: flag is not defined
Once you do that you will receiving another error:
Uncaught ReferenceError: flag is not defined
For the line:
flag = flag+1;
This is because you have not defined your flag variable, this can be fixed by defining var flag; at the top of your first.
Demo
jsFiddle
var all ="ABCDEFGHIJKLMNOPQRSTUVWXYZa{}[];:></?bcdefghijklmnopqrstuvwxyz0123+_)(*&^%$##!~`456789";
var old_text;
var flag = 0;
function randChar() {
"use strict";
return all.charAt(Math.floor(Math.random()*all.length));
}
function main() {
"use strict";
old_text = document.getElementById("text").innerText;
var counter = Math.floor(Math.random()*document.getElementById("text").innerText.length);
var $_inter = setInterval(function() {
var text = document.getElementById("text");
text.innerHTML = text.innerHTML.substring(0, 5) + randChar() + text.innerHTML.substring(5);
setTimeout(function(){
text.innerHTML = old_text;
},200);
flag = flag+1;
}, 350);
}
window.onload = main;
Error in Firefox
With the above code we're still receiving the original error in Firefox. This is because Firefox doesn't implement innerText. This can be fixed by using either .textContent or .innerHTML.
jsFiddle
old_text = document.getElementById("text").textContent;
var counter = Math.floor(Math.random()*document.getElementById("text").textContent.length);
// or
old_text = document.getElementById("text").innerHTML;
var counter = Math.floor(Math.random()*document.getElementById("text").innerHTML.length);

var all ="ABCDEFGHIJKLMNOPQRSTUVWXYZa{}[];:></?bcdefghijklmnopqrstuvwxyz0123+_)(*&^%$##!~`456789";
var old_text;
function randChar() {
"use strict";
return all.charAt(Math.floor(Math.random()*all.length));
}
function main() {
"use strict";
old_text = document.getElementById("text").innerText;
var $_inter = setInterval(function() {
var text = document.getElementById("text");
text.innerHTML = text.innerHTML.substring(0, 5) + randChar() + text.innerHTML.substring(5);
setTimeout(function(){
text.innerHTML = old_text;
},200);
}, 350);
}
window.onload = main;
Just get rid of flag and counter. Initialize old_text in the onload listener.

Related

javascript - replace text with tags

i do not know much about javascript searched long, but didn't get the reslut i need.
i want to replace on page load this
<p>---SOMERANDOMTEXT:::</p>
with
<strong>SOMERANDOMTEXT</strong>
played with this an many other snippets..
<script type="text/javascript">
window.onload = function() {
function myscript() {
input = '---';
output='New Text';
document.body.innerHTML = document.body.innerHTML.replace(input,output);
}
}
</script>
Here is the fast and fool proof way of replacing <p> tags with <strong> tags:
var ps = document.getElementsByTagName('p');
for (var i = ps.length; i--;) {
var strong = document.createElement('strong'),
p = ps[i];
while (p.firstChild) {
strong.appendChild(p.firstChild);
}
p.parentNode.insertBefore(strong, p);
p.parentNode.removeChild(p);
}
If you need to change the text accordingly, place something like that in the while loop:
if (p.firstChild.nodeType === 3) {
p.firstChild.nodeValue = p.firstChild.nodeValue.replace(/[-:]{3}/g, '');
}
DEMO: http://jsfiddle.net/5m9Qm/1/
You need to call your myscript function like this -
window.onload = function() {
myscript();
}
function myscript() {
var input = '---';
var output='New Text';
document.body.innerHTML = document.body.innerHTML.replace(input,output);
}
You are declaring a function myscript but never invoking it. Try this (untested) code:
<script>
window.onload = function(){
var p = document.querySelector('p');
var strong = document.createElement('strong');
strong.innerHTML = 'replaced';
p.parentNode.replaceChild(strong,p);
})
</script>
Note this requires modern browsers.
You can use a regex.
Try:
output = document.body.innerText.replace(/[-:]{3}/g, '');
document.body.innerHTML = document.body.innerHTML.replace(/<p>---.*:::<\/p>/, '<strong>' + output + '</strong>');
DEMO

How to call javascript function only once during window.onscroll event?

function getH4() {
var xyz = document.getElementsByClassName('bucket_left');
for(var i=0;i<xyz.length;i++){
var x=document.getElementsByTagName("h4")[i].innerHTML;
var current_bucket = xyz[i];
var y=current_bucket.firstChild.href;
var newdiv = document.createElement('div');
newdiv.innerHTML = ""+x+"";
newdiv.className = "hover_title_h4";
current_bucket.appendChild(newdiv);
}
}
window.onscroll=getH4;
In above code i want to append new div in set of divs having class bucket_left and this divs generated from infinite scrolling. above code is working fine but on scroll it appends so many divs.
so how do i append only once ?
Add the following line at the end of your function:
function getH4() {
// ...
window.onscroll = null;
}
create a global boolean variable and set it to false. again set it to true in the window scroll event and chk the variable is false using a if block. put your code inside that if block.
var isScrolled = false;
function getH4() {
if(!isScrolled){
//your code
}
isScrolled = true
}
You only have to set the onscroll property to none as following at the end of you JavaScript function:
window.onscroll = null;
Now when the script executes for the first time, it will perform its function and the above line will set the onscroll to null and thus will not invoke any event on scroll of your mouse and so your function wont be invoked again and again on the event except for the first time.
Or you could handle it logically by setting a public var say var check = 0 and then set the variable to 1 when entered for the first time. So you need to check the value of check and based on that execute the function
var check = 1;
function getH4() {
if(check==1)
{
var xyz = document.getElementsByClassName('bucket_left');
for(var i=0;i<xyz.length;i++){
var x=document.getElementsByTagName("h4")[i].innerHTML;
var current_bucket = xyz[i];
var y=current_bucket.firstChild.href;
var newdiv = document.createElement('div');
newdiv.innerHTML = ""+x+"";
newdiv.className = "hover_title_h4";
current_bucket.appendChild(newdiv);
}
check=0;
}
}
you can try this:
when scrolling,the check equal false, and the append event will happen just once;
when the scroll end(mouseup or mouseout), the check equal true, you can append again.
var check = true;
function getH4(event) {
event.target.onmouseup = function() {
check = true;
}
event.target.onmouseout = function() {
check = true;
}
if (check) {
var xyz = document.getElementsByClassName('bucket_left');
for(var i=0;i<xyz.length;i++){
var x=document.getElementsByTagName("h4")[i].innerHTML;
var current_bucket = xyz[i];
var y=current_bucket.firstChild.href;
var newdiv = document.createElement('div');
newdiv.innerHTML = ""+x+"";
newdiv.className = "hover_title_h4";
current_bucket.appendChild(newdiv);
}
check = false;
}
window.onscroll=getH4

Using a variable from one function in an other - think im missing something

this is most probably simple but im struggling a little is it possible to do something like the below becasue its not alerting in the 2nd function.
function func1() {
var test = 5;
var testAgain = 8;
}
function func3() {
func1();
alert(test);
}
edit:
Thank you all for your comments, however i cant seem to get it to work.
i below is the code i am trying to get this to work in
it does not seem to want to pass the vars from setImageReelWidth, and just alerts 0 when it gets to rotate = function () or $(".paging a").click(function (). so i click and it alerts 4 (which is correct) and then when it runs it twice again i just get 0
var divWidth = 0;
var slideTotal = 0;
var divReelWidth = 0;
function setImageReelWidth() {
var divWidth = $(".window").width();
var slideTotal = $(".slide").size();
var divReelWidth = divWidth * slideTotal;
alert(slideTotal);
//Adjust the image reel to its new size
$(".image_reel").css({ 'width': divReelWidth });
}
$(document).ready(function () {
//////////////////////////// INITAL SET UP /////////////////////////////////////////////
//Get size of images, how many there are, then determin the size of the image reel.
//var divWidth = $(".window").width();
//var slideTotal = $(".slide").size();
//var divReelWidth = divWidth * slideTotal;
//Adjust the image reel to its new size
//$(".image_reel").css({ 'width': divReelWidth });
//set the initial not active state
$('#prev').attr("class", "not_active");
//////////////////////////// SLIDER /////////////////////////////////////////////
//Paging + Slider Function
rotate = function () {
setImageReelWidth();
alert(slideTotal);
var triggerID = $slideNumber - 1; //Get number of times to slide
var image_reelPosition = triggerID * divWidth; //Determines the distance the image reel needs to slide
//sets the active on the next and prev
if ($slideNumber == 1) {
$('#prev').attr("class", "not_active")
$('#next').attr("class", "active")
}
else if ($slideNumber == slideTotal) {
$('#next').attr("class", "not_active");
$('#prev').attr("class", "active");
}
else {
$('#prev').attr("class", "active")
$('#next').attr("class", "active")
};
//Slider Animation
$(".image_reel").animate({
left: -image_reelPosition
}, 500);
};
//////////////////////////// SLIDER CALLS /////////////////////////////////////////////
//click on numbers
$(".paging a").click(function () {
setImageReelWidth();
alert(slideTotal);
setImageReelWidth();
$active = $(this); //Activate the clicked paging
$slideNumber = $active.attr("rel");
rotate(); //Trigger rotation immediately
return false; //Prevent browser jump to link anchor
});
Making the variable available to both methos, by defining it globally, like Rory suggested in his answer, is fine.
Another solution would be to return it from the first function and use it in the second like this:
function func1() {
var test = 5;
return test;
}
function func3() {
var x = func1();
alert(x);
}
EDIT
Another way to do it, is writing a factory function to create func3:
var func3 = (function(){
var test;
function func1() {
test = 5;
}
return function() {
func1();
alert(test);
}
})();
What happens here is the following:
I created a function, that gets executed right away:
(function(){
// ...
})();
In there, I have the variable test and another function called func1 and I return a function that gets bound to the variable func3. func3 has now access to the var test as well as func1 but nothing outside that factory function I wrote can access them.
Check out the fiddle I created: enter link description here.
Stuff like this is a little hard to understand at first, but it's really the power of JavaScript (IMHO).
You need to declare the variable with global scope.
var test = 0;
function func1() {
test = 5;
}
function func3() {
func1();
alert(test);
}
Further reading on variable scope in javascript

adding html within var string?

Say I have
var b = 'I am a JavaScript hacker.'
How can I do this ?
var b = 'I am a JavaScript hacker.'
Is this dooable ?
I thought the question was clear. Apologies if it wasnt.
Fiddle here http://jsfiddle.net/ozzy/vWYQ2/
$(function() {
var mem = $("#TA").html();
$("#TA").hover(function() {
$(this).stop().html( 'I am a JavaScript hacker.' );
}, function() {
$(this).stop().html( mem );
});
});
I think you want something like this
My code
Edited: Due to the flickering issue.
um... yes? that will give you a variable named b which holds 'I am a JavaScript hacker.'
Code from http://jsfiddle.net/vWYQ2/2/, this removes the hyperlink once mouse is out.
HTML
<div id="TA" onmousemove="changetext();" onmouseout="restore();">I am a JavaScript hacker.</div>
JavaScript
var originalBlock = document.getElementById("TA").innerHTML;
var timer;
function changetext()
{
var id = document.getElementById("TA");
if(originalBlock == null) originalBlock= id.innerHTML;
var text = id.innerHTML;
id.innerHTML = text.replace("JavaScript hacker", "<a href='foo.php'>JavaScript hacker</a>");
if(timer != null)
clearTimeout(timer);
}
function restore()
{
timer = setTimeout(function()
{
document.getElementById("TA").innerHTML = originalBlock;
}, 1000);
}

Help converting JavaScript click function to onLoad

I'm trying to convert a JavaScript function that ran off a click event to launch on page load and window resize. As you can see below, I commented out the section governing the click event and added the last line "window.onload," and manually added the class="resizerd" to the element it was working with.
The function isn't running at all. Chrome's Dev tools are showing "Uncaught TypeError: Cannot set property 'prevWidth' of undefined" Did I mess up the syntax somewhere? Any advice for how to launch this on load?
Thank you!
//var clicked = document.getElementById("buttonImportant")
var resizeeContainer = document.getElementById('video_container');
var resizee = resizeeContainer.getElementsByTagName('video')[0];
/*clicked.addEventListener('click',function(){
if( resizeeContainer.className.lastIndexOf("resizerd")>=0 ){
}
else
{
resizeeContainer.className="resizerd";
}*/
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
//},false);
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
var RESIZER = function(){
this.prevWidth = resizee.offsetWidth;
this.prevHeight = resizee.offsetHeight;
this.resizee = resizeeContainer.getElementsByTagName('video')[0];
this.resizeeContainer = resizee.parentNode;
this.resizeeStyle = this.resizee.style;
var ratio = this.resizee.offsetHeight/this.resizee.offsetWidth;
var that = this;
this.Init = function(){
if( that.resizeeContainer.className.lastIndexOf("resizerd")>=0 )
{
var resizeeContOffsetWidth = that.resizeeContainer.offsetWidth;
var resizeeOffsetWidth = that.resizee.offsetWidth;
var resizeeContOffsetHeight = that.resizeeContainer.offsetHeight;
var resizeeOffsetHeight = that.resizee.offsetHeight;
if(that.prevWidth!= resizeeContOffsetWidth)
{
that.prevWidth = resizeeContOffsetWidth;
var desired = resizeeContainer.offsetHeight/resizeeContainer.offsetWidth;
if(desired>ratio){
that.resizeeStyle.width=resizeeContOffsetWidth*desired+resizeeContOffsetWidth*desired+"px";
that.resizeeStyle.left = -1*(resizeeOffsetWidth-resizeeContOffsetWidth)/2+'px';
}
else{
that.resizeeStyle.cssText="width:100%;height:auto;position:fixed;";
}
}
if(that.prevHeight!=resizeeContOffsetHeight)
{
that.prevHeight = resizeeContOffsetHeight;
var desired = resizeeContOffsetHeight/resizeeContOffsetWidth;
if(desired>ratio){ console.log(ratio);
//that.resizeeStyle.top = '0px';
that.resizeeStyle.left = -1*(resizeeOffsetWidth-resizeeContOffsetWidth)/2+'px';
that.resizeeStyle.width = resizeeContOffsetHeight*desired+resizeeContOffsetHeight/desired+'px';
}
else
{
that.resizeeStyle.top = -1*(resizeeOffsetHeight-resizeeContOffsetHeight)/2+'px';
}
}
}
};
};
var myResizerObject = new RESIZER();
window.onresize = myResizerObject.Init;
window.onload = myResizerObject.Init;
Did you try to execute the function through the <body> tag?
Like:
<body onload="myfunction();">
Try calling the entire resize javascript function in the OnLoad="myfunction();" event of the Body of the page. I have done this to resize the page everytime it loads and it works just fine.
You have this line:
myResizerObject.prevWidth = resizee.offsetWidth;
That is probably giving the error. You've done nothing to declare myResizerObject so it cannot have a property prevWidth.
Somewhere down there you do
var myResizerObject = new RESIZER();
I suspect you want those lines in a more reasonable order :)
Such code should work just fine:
var myResizerObject = new RESIZER();
function UpdateResizerObject() {
var resizeeContainer = document.getElementById('video_container');
var resizee = resizeeContainer.getElementsByTagName('video')[0];
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
}
window.onload = function() {
UpdateResizerObject();
};
window.onresize = function() {
UpdateResizerObject();
};
Have it after you define the RESIZER class though.
Your mistake was calling the object instance variable before creating it.
Edit: some basic debug.. add alerts to the function like this:
this.Init = function(){
alert("Init called.. container: " + that.resizeeContainer);
if (that.resizeeContainer)
alert("class: " + hat.resizeeContainer.className);
if( that.resizeeContainer.className.lastIndexOf("resizerd")>=0 )
{
...
}
}
And see what you get.

Categories

Resources