How do I change the text displayed on a website? - javascript

What I want to do is change one word of text on my webpage to run through a list of words.
ie:
<p>My favorite hobby is <u>fishing</u>!</p>
Where "fishing" would change after about 2 secs to the next word of a list of hobbies.
The closest example I've found is this
<div id="welcome">
<h3>Welcome, welcome, welcome!</h3>
<h3>Hang around a bit (for a surprise).</h3>
</div>
function ChangeIt() {
var newcontent = '
<h1>Click here ' +
'for a web page with more of the same.</h1>';
WriteContentIntoID("welcome",newcontent);
}
setTimeout("ChangeIt()",20000);
But I can't get it to work either.

Here's something simple using setInterval():
<p>My favorite hobby is <span id="ch">fishing</span>!</p>
<script>
var activities = ['eating', 'burping','coding'];
var i=0;
setInterval(function(){
document.getElementById("ch").innerHTML = activities[i];
if (i < activities.length-1) {
i++;
} else {
i=0;
}
}, 1000);
</script>
FIDDLE Demo
EDIT: changed to make it loop forever.

Use this:
<p>My favorite hobby is <u>fishing</u>!</p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function getnewword(){
return "me";// fix this section with getting new word!
}
function ChangeIt() {
$("p u").html(getnewword());
setTimeout("ChangeIt()",2000);
}
setTimeout("ChangeIt()",2000);
<script>

Programming is cool. You should try with some beginner JavaScript tutorials like http://www.w3schools.com/js/.
You must encapsulate your script with script tag and you must use selectors (like document.getElementById).
This is the full code:
<div id="welcome">
<h3>Welcome, welcome, welcome!</h3>
<h3 id="hobby">Hang around a bit (for a surprise).</h3>
</div>
<script>
// we start with 0
var currentHobby = 0;
function ChangeIt() {
// hobbies array
var hobbies = ["fishing", "eating", "drinking", "programming"];
// we save the current hobby in hobbyString and increment the currentHobby number
var hobbyString = hobbies[currentHobby];
currentHobby++;
// if the currentHobby number is too big, we start with 0 again
if(currentHobby >= hobbies.length) {
currentHobby = 0;
}
document.getElementById("hobby").innerHTML = "My favourite hobby is " + hobbyString;
}
setInterval("ChangeIt()",2000);
</script>

HTML PART
I am going to <span id="changingtext">InitialWord</span>
Javascript Part - You Need JQuery and call the following on onLoad
var texts = ["France", "Italy", "Ireland", "Wales"];
var count = 0;
function updateval() {
$("#changingtext").text(texts[count]);
count < 4 ? count++ : count = 0;
}
setInterval(updateval, 2000);
Working JS Fiddle Link Click Here
Click on the Javascript setting button on JsFiddle to check the settings put in use.

Related

How to make dynamic changes in HTML?

So I want to add to a variable every time someone clicks a button on my website. I am very new to HMTL so I don't know how to do this. All the examples I've googled just change text into other text and not adding to a variable.
If someone would like to enlighten me on how to do this I would greatly apricate it.
function changeIt() {
document.getElementById('test').innerHTML = "<h2>Congrats</h2>";
}
<div id="test">
<b> <var> Test </ var> </b>
</div>
<button onclick="changeIt()">Test</button>
var sum = 0;
function changeIt() {
sum++;
document.getElementById('test').innerHTML = `<h2> ${sum} </h2>`;
}
<div id="test">
<b> <var> Test </ var> </b>
</div>
<button onclick="changeIt()">Test</button>
The code you've written in document.innerHTML is correct. For making it dynamic and to add a new Congrats onto the screen instead of just modifying the old one, you need to keep a global counter and loop over it.
let count = 0;
function changeIt() {
count++;
for (let i=0;i<count;i++) {
document.getElementById('test').innerHTML = '';
let h2 = document.getElementById('test').createElement;
h2.innerHTML = "Congrats";
document.getElementById('test').appendChild(h2);
}
}
Since you are calling the changeIt function on every button click it will let you update the count and will loop over the count to add the Congrats 'count' number of times to your div.

While Loop with AngularJS?

I'm trying to mimic the while loop of plain Javascript in AngularJS. I simply want to call the createPlant() method x number of times according to the value of the quantity input, when the "add" button is clicked, as follows (it adds to an array 'plants'):
$("#add").on("click", function() {
var i = 0;
while (i < $("#pQuantity").val()) {
createPlant();
i += 1;
};
In Angular I have:
HTML
<button ng-click="addPlant()" type="button">Add</button>
And I'm not sure how the script would look but this is what I wrongly put:
JS
var i = 0;
while (i < $("#pQuantity").val()) {
$scope.addPlant = function() {
var plant = {name: $("#pVariety").val()};
$scope.plants.unshift(plant);
};
i += 1;
};
I support what #dfsq told you in the comment. Do not use jQuery if you are using angular... unleash the angular power! :P
For your solution, you should do something like this:
Your JS:
$scope.result="";
$scope.addPlant = function(){
for (i=0; i<$scope.someValue;i++){
//do something
$scope.result=$scope.result+i.toString()+",";
}
};
HTML:
<body ng-controller="MainCtrl">
<input type=number ng-model="someValue" />
<button ng-click="addPlant()">CLICK ME</button>
<div>{{result}}</div>
</body>
Plunker sample

Getting the value from an HTML button using JavaScript

I am making a calculator, I have already created the calculator in html and css but I am trying to move forward by making the button clicks register in the display which is what my problem is right now. I am fairly new to JavaScript so if someone could point me in the right direction on how to do it or where to find the answer I would appreciate it.
This is a the portion I am working on, trying to get button '7' to register so I can do the others.
<div class="container-fluid calc" >
<div class="display">
<label type="text" id="screen">0</label>
<div class="buttons">
<button onClick='calculate()' id='myButton'>7</button>
<button>8</button>
<button>9</button>
Here is the JS I put together
function calculate(){
var num = document.getElementById('#myButton').contentValue;
document.getElementById('screen').innerHTML = num;
}
calculate();
You need to update from
var num = document.getElementById('#myButton').contentValue;
to
var num = document.getElementById('myButton').innerHTML;
You should use the .innerHTML function instead of the .contentValue function to do this, also, you shouldn't use a # in document.getElementById this is used in jQuery, so just the ID is enough
function calculate(){
var num = document.getElementById('myButton').innerHTML;
document.getElementById('screen').innerHTML = num;
}
calculate();
Hope this helps!
Update
function calculate(){
var num = document.getElementById('#myButton').contentValue;
document.getElementById('screen').innerHTML = num;
}
to
function calculate(){
var num = document.getElementById('myButton').innerText;
document.getElementById('screen').innerText = num;
}
Another option is you can is data attribute like this :
<button onClick='calculate()' id='myButton' data-value="7">7</button>
and get it like this :
$("#myButton").attr("data-value");

How do i check if a text is almost the same as required

I want to check if the value of my textarea is almost the same as requires , for example :
I have a HTML code :
<textarea class="ab" placeholder="Type here"></textarea>
<div class="result">
</div>
and a Jquery code :
$(document).ready(function(){
$(".btn").click(function(){
var a = $(".ab").val();
var b = $(".result").html();
/* */
if(a.indexOf('Which of the following is generally true about Open Source software?') >= 0){$('.result').html('Its usually developed on a volunteer basis and anyone is free to change it (correct).');} /* */
else{
$(".result").html("error");
}
});
});
this code doesn't work as what i want actually , this is just what i tried to make . But the thing i want is for example when the value of the $('.ab') is almost the same as the text Which of the following is generally true about Open Source software? like the following is generally true or true about the Open Source , the $(".result") still have the html as Its usually developed on a volunteer basis and anyone is free to change it (correct).
So how do i do that , thanks for your help
Try splitting input text into array , using $.each() to iterate input words , if input words match at least five words in selected phrase , return true , else return false at if ; e.g.; try typing or pasting at textarea
the following is generally true or true about the Open Source
$(document).ready(function() {
$(".btn").click(function() {
var a = $(".ab");
var b = $(".result");
var arr = a.val().split(/\s+/);
var n = 0;
var phrase = "Which of the following is generally true about Open Source software?";
$.each(arr, function(key, val) {
if(phrase.indexOf(val) >= 0) ++n;
})
if (n >= 5) {
b.html('Its usually developed on a volunteer basis and anyone is free to change it (correct).');
}
else {
b.html("error");
};
a.val(""); n = 0;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea class="ab" placeholder="Type here"></textarea>
<div class="result"></div>
<button class="btn">click</button>
Actually it should be:
$(document).ready(function(){
$(".btn").click(function(){
var a = $(".ab").val();
var b = $(".result").html();
var c = 'Which of the following is generally true about Open Source software?';
console.log(c.indexOf(a));
if(c.indexOf(a) >= 0){
$('.result').html('Its usually developed on a volunteer basis and anyone is free to change it (correct).');
} else {
$(".result").html("error");
}
});
});
<textarea class="ab" placeholder="Type here">following is generally true about Open Source</textarea>
<div class="result"></div>
<button class="btn">test</button>

Looping through array using a button

Ok, in essence I want to create a short quiz that has a next and previous button. I want to loop through two arrays, questions and choices, and have a score at the end. I have read chapters on the DOM and Events and it is just not clicking apparently.
Really I need a little bit of code that shows a concrete example of how to manipulate the DOM. What I have so far are only the arrays, and a function declaring that x is in fact getting my element by id. haha.
Sorry I don't have more code to give. I tried to attach the id to a paragraph, and then get it by it's id and document.write the array, but that replaces the button. If you run the code below you'll see what I'm saying.
<!DOCTYPE html>
<html>
<head>
<title>Bom</title>
</head>
<body>
<input type="button" value="Iterate" id="myButton" onclick="iter_onclick()">
<p id="qArray">Some Text</p>
<script>
var qArray = ["Who is my dog?", "who is the prez?", "Who is my girlfriend?", "Who am I?"];
var cArray = [["Bill","Billy", "Arnold", "Tyler"],["Oz"," Buffon","Tupac","Amy"],["Tony Blair","Brack Osama","Barack Obama","Little Arlo"],["Emma Stone","Tony the Tiger","","The Smurf Girl"]];
function iter_onclick () {
var x = document.getElementById("qArray");
document.write("Hello World");
}
</script>
</body>
</html>`
Like I said, this is my first attempt at truly manipulating the DOM, and I know what I want to do. I just don't know how to do it. I am understanding all the syntax and events and objects and such. But, I'm not really sure how to apply it. Also, no Jquery. I want to know how to create applications with Javascript and then work my way into Jquery. Thanks people.
This will loop through your questions, hope this helps you to proceed.
var qArray = ["Who is my dog?",
"who is the prez?",
"Who is my girlfriend?",
"Who am I?"];
var cArray = [
["Bill", "Billy", "Arnold", "Tyler"],
["Oz", " Buffon", "Tupac", "Amy"],
["Tony Blair", "Brack Osama", "Barack Obama", "Little Arlo"],
["Emma Stone", "Tony the Tiger", "Amy Dahlquist", "The Smurf Girl"]
];
var index = 0;
function iter_onclick() {
//if this is the last question hide and displays quiz ends
if (index >= qArray.length) {
document.getElementById('qArray').innerHTML = '<div>Quiz End, Thank you</div>'
document.getElementById('myButton').style.visibility = 'hidden ';
return false;
}
var html = ' <div> ' + qArray[index] + ' </div> <div>';
for (var i = 0; i < cArray[index].length; i++) {
html += '<label><input type="radio" name="ans" value="'
+ cArray[index][i] + '"/ > ' + cArray[index][i] + ' </label>';
}
html += '</div > ';
document.getElementById('qArray').innerHTML = html;
index++;
}
Here's a very basic example you can work from. This modifies the existing DOM items. You cannot use document.write() on a document that is already loaded or it will clear everything you have and start over and it's not the most efficient way to put content into the DOM.
This example has a number of fields on the page, it loads a question and then checks the answer when you press the next button.
HTML:
<div id="question"></div>
<input id="answer" type="text"><br><br>
<button id="next">Next</button> <br><br><br>
Number Correct So Far: <span id="numCorrect">0</span>
Javascript (in script tag):
var qArray = ["Who is my dog?", "who is the prez?", "Who is my girlfriend?", "Who am I?"];
var cArray = [["Bill","Billy", "Arnold", "Tyler"],["Oz"," Buffon","Tupac","Amy"],["Tony Blair","Brack Osama","Barack Obama","Little Arlo"],["Emma Stone","Tony the Tiger","Amy Dahlquist","The Smurf Girl"]];
var questionNum = -1;
var numCorrect = 0;
function loadQuestion() {
++questionNum;
if (questionNum >= qArray.length) {
alert("all questions are done");
} else {
document.getElementById("question").innerHTML = qArray[questionNum];
document.getElementById("answer").value = "";
}
}
loadQuestion();
function checkAnswer() {
var answer = document.getElementById("answer").value.toLowerCase();
var allowedAnswers = cArray[questionNum];
for (var i = 0; i < allowedAnswers.length; i++) {
if (allowedAnswers[i].toLowerCase() == answer) {
return true;
}
}
return false;
}
document.getElementById("next").addEventListener("click", function(e) {
if (checkAnswer()) {
++numCorrect;
document.getElementById("numCorrect").innerHTML = numCorrect;
loadQuestion();
} else {
alert("Answer is not correct");
}
});
Working demo: http://jsfiddle.net/jfriend00/gX2Rm/

Categories

Resources