trying to get my button to change text without user interaction javascript - javascript

i made a button function that has a button with a word and when its clicked the definition shows. but now i'm trying to make it so that the buttons shows the definition every couple seconds with "SetInterval" without needing to be clicked and i don't know how to go about doing so can you please help.
'use strict';
//below is the function for the even
$(document).ready(function() {
//
function salutationsHandler(evnt) {
let box = $("#message-box");
if (box.hasClass("hidden")) {
box.attr("class", "");
$(evnt.target).text("1.Salutation");
} else {
box.attr("class", "hidden");
$(evnt.target).text('a greeting in words or actions');
}
}
//end of function
setInterval(salutationsHandler, 1000);
//start of another
function DiffidenceHandler(evnt2) {
let box2 = $("#message-box2");
if (box2.hasClass("hidden")) {
box2.attr("class", "");
$(evnt2.target).text("2.Diffidence");
} else {
box2.attr("class", "hidden");
$(evnt2.target).text("the quality of being shy");
}
console.log(evnt2);
}
//lets me target id
let salutationsGrab = $('#Salutations');
// adds event to said id
// event listeners grab events from functions
salutationsGrab.on('click', salutationsHandler);
let DiffidenceGrab = $("#Diffidence");
DiffidenceGrab.on("click", DiffidenceHandler);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>hello welcome to our dictionary</h1>
<h2>Click on button to reveal definition of word shown</h2>
<button id="Salutations">1.Saluation</button>
<div id="message-box"></div>
<br>
<button id="Diffidence">2.Diffidence</button>
<div id="message-box2"></div>
<br>

The function salutationsHandler needs the event object generated by an event to work. Instead of calling the function directly, you can use jQuery's .trigger() to "click" the button.
function salutationsHandler(evnt) {
const box = $("#message-box");
const target = $(evnt.target);
if (box.hasClass("hidden")) {
box.removeClass("hidden");
target.text("1.Salutation");
} else {
box.addClass("hidden");
target.text('a greeting in words or actions');
}
}
let salutationsGrab = $('#Salutations');
salutationsGrab.on('click', salutationsHandler);
setInterval(() => salutationsGrab.trigger('click'), 1000);
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>hello welcome to our dictionary</h1>
<h2>Click on button to reveal definition of word shown</h2>
<button id="Salutations">1.Saluation</button>
<div id="message-box">a greeting in words or actions</div>

Related

Load a script using nodes included by another script

I need to make a web page with a lot of content. In order to be more efficient when modifying this content, I decided to put it in separate files and then include these files, following this tutorial: https://www.w3schools.com/howto/howto_html_include.asp.
For example one of these files may contain some clickable links to book descriptions, which are modal boxes. So I need to get them in a loading script to get these clickable links and make them trigger some events. But it seems this loading script is called before JavaScript gets the included nodes, even if I add an event listener after reading some threads (I tried to run it at 'DOMContentLoaded' or 'load') : document.getElementById or document.getElementsByClassName still returns null so it fails to define an onclick function. Let me show an example code:
script.js
function includeHTML() { /* Some code replacing the div by some-content.html, which is : <a id="clickable">Hello</a> */}
var button = null
window.addEventListener('load', function() {
button = document.getElementById("clickable");
button.onclick = function() { alert('Hello'); }
});
index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<p>Here is a trigger button : </p>
<div include-html="some-content.html"></div>
<script>includeHTML();</script>
</body>
</html>
On Firefox, this will fail on defining button.onclick as button is still null.
Any idea on how to fix it?
Not only should I be adding links, but also modal boxes. Here is a script code, more complete, for what my guess was:
script.js
var boxNames = ["bibliography", "about", "book1", "book2" ];
var boxes = null /* Contains the boxes to be displayed */
var trigs = null /* Contains the trigger buttons for each box */
var close = null /* Contains the close buttons for each box */
function setTrigger(i) {
trigs[i].onclick = function() { setBoxVisible(true, i); }
}
function setClose(i) {
trigs[i].onclick = function() { setBoxVisible(false, i); }
}
function load() {
boxes = new Array(4);
trigs = new Array(4);
close = new Array(4);
for(var i = 0; i < boxNames.length; i++) {
boxes[i]=document.getElementById(boxNames[i]+"-box");
trigs[i]=document.getElementById(boxNames[i]+"-trig");
close[i]=document.getElementById(boxNames[i]+"-close");
setTrigger(i); setClose(i);
}
}
window.onload = function() { load(); }
For the code of includeHTML(), you can have a look at the tutorial I shared, I copy/pasted.
I think this kind of function would be more elegant if dealing with such stuff, but I would need it to be launched once everything is loaded, as if I was running it manually.
Your code only added the event listener when the page was loading, likely before the link existed.
You need to delegate from the nearest static container.
Here in your code it is document
Give the link a class instead of ID and do
window.addEventListener('load', function(e) {
document.addEventListener('click', function(e) {
const tgt = e.target;
if (tgt.classList.contains("clickable")) {
e.preventDefault(); // because it is a link
alert('Hello');
}
});
});
<a class="clickable" href="#">Click</a>
Update after new code
You overwrite the trigs code
You can very simply extend my code so you do not need to loop
window.addEventListener('load', function(e) {
document.addEventListener('click', function(e) {
const tgt = e.target;
if (tgt.classList.contains("clickable")) {
e.preventDefault(); // because it is a link
alert('Hello');
}
else if (tgt.classList.contains("box")) {
e.preventDefault(); // because it is a link
const [id, what] = tgt.id.split("-")
console.log(id)
if (what === "trig") {
document.getElementById(id).classList.remove("hide")
}
else if (what === "close") {
document.getElementById(id).classList.add("hide"); // or tgt.closest("div").classList.add("hide")
}
}
});
});
.hide { display:none; }
<a class="clickable" href="#">Click</a>
<hr/>
<a class="box" id="bibliography-trig" href="#">Trigger Biblio</a>
<a class="box" id="about-trig" href="#">Trigger About</a>
<div id="bibliography" class="hide">Biblio
<a class="box" id="bibliography-close" href="#">Close</a>
</div>
<div id="about" class="hide">About
<a class="box" id="about-close" href="#">Close</a>
</div>

How do I add a button to a div class on load from Javascript? [duplicate]

This question already has answers here:
How to add onload event to a div element
(26 answers)
Closed 5 years ago.
For an assignment, I cannot touch the HTML code and am editing an external JS file. I have to refer the code to an existing class and turn that into a button to run a script.
The has to be ran on load to transform an element with a given id into a button that can also run a function on click.
So let's say the we have id="bar",
how do I go about it?
My code doesn't work at all.
document.getElementById("bar").onload = function () { myFunction() };
function myFunction() {
document.getElementById("bar").innerHTML = "<button></button>";
}
Why don't you just execute your script as the DOM is ready? To do so,
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("bar").innerHTML = "<button></button>";
}, false);
You just need a createElement function.
This works:
document.addEventListener("DOMContentLoaded", function(){
var button = document.createElement("button");
button.innerHTML = "This is a button";
// assuming the Div's ID is bar
var div = document.getElementById('bar');
div.appendChild(button);
//the following function will alert a window when the button is clicked
button.addEventListener ("click", function() {
alert("Button was clicked");
});
});
Updated Codepen
I think this is bit tha you needed
var bar = document.getElementById('bar');
window.onload = function() {
var barInner = bar.innerHTML;
bar.innerHTML = '<button>' + barInner + '</button>';
}
bar.onclick = function() {
alert("Hello\nHow are you?");
};
document.getElementById("bar").onload = myFunction();
function myFunction() {
document.getElementById("bar").innerHTML = "<button>Button</button>";
}
There you go!
Not every single HTML element has a load event.
Only some of them are concerned, such as the window, an image... etc
Have a look here on MDN to learn more about this.
Here is a simple snippet resolving all what you mentioned.
window.addEventListener("load", () => {
// you can put your entire script in here.
var elt = document.getElementById("bar"),
button = document.createElement("button");
button.textContent = elt.textContent;
button.onclick = callback;
elt.textContent = '';
elt.appendChild(button);
function callback() {
console.log("The button has been clicked");
}
});
<div id="bar" style="background: beige; height: 2em">Click me</div>
In the previous snippet, I am appending the button in the element. But if the matter is really to transform it into a button, there we go:
window.addEventListener("load", () => {
// you can put your entire script in here.
var elt = document.getElementById("bar"),
container = elt.parentNode,
button = document.createElement("button");
button.id = elt.id; // if you want to keep the id
button.textContent = elt.textContent;
button.onclick = callback;
container.removeChild(elt);
container.appendChild(button);
function callback() {
console.log("The button has been clicked");
}
});
<div style="background: #fee; height: 2em">
<div id="bar" style="background: beige; height: 2em">Click me</div>
</div>

Change button's text and function

I'd like to do the following. I got a button like this:
<button class="uk-button uk-position-bottom" onclick="search.start()">Start search</button>
The JS part is this:
var search = new SiteSearch();
Now I'd like to do this:
Once clicked, the label of the button should show Stop search. And the called function should be search.stop(). If the user clicks Stop search, the button should be the Start search button again.
How can I do this in an elegant way?
Here you have working code snippet for this:
$(document).ready(function() {
function startSearch() {
console.log('Here your start search procedure');
}
function stopSearch() {
console.log('Here your stop search procedure');
}
$('.search-button').click(function() {
var buttonSelector = '.search-button';
if($(buttonSelector).hasClass('searching')) {
$(buttonSelector).removeClass('searching');
$(buttonSelector).text('Start search');
stopSearch();
} else {
$(buttonSelector).addClass('searching');
$(buttonSelector).text('Stop search');
startSearch();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="uk-button uk-position-bottom search-button">Start search</button>
Here's what I'd do: add an ID to the button, then query that button in the script and add a click listener to it. The script would keep track of whether or not a search is being done, then call search.start/stop() and set the button text accordingly.
<button id="search-button" class="uk-button uk-position-bottom">
Start search
</button>
<script>
const search = new SiteSearch()
const searchButton = document.querySelector('#search-button')
let searching = false
searchButton.addEventListener('click', () => {
if (!searching) {
search.start()
searching = true
searchButton.textContent = 'Stop search'
} else {
search.stop()
searching = false
searchButton.textContent = 'Start search'
}
})
</script>
You can do this easily like below:
var $elem = $('.uk-button.uk-position-bottom');
var search = {
//start function
start: function(){
//change the text
$elem.text('Stop search');
//change the click function
$elem.attr('onclick', 'search.stop()');
console.log('start clicked');
},
//stop function
stop: function(){
//change the text
$elem.text('Start search');
//change the click function
$elem.attr('onclick', 'search.start()');
console.log('stop clicked');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="uk-button uk-position-bottom" onclick="search.start()">Start search</button>
i think this answer is the same as a previus posted question:
https://stackoverflow.com/a/10671201/7387232
with the little add that when the button is clicked the button has to change the onclick propriety maybe with a check
object.onclick = function() {
if(search.isRunning()) search.stop();
}
and viceversa :-)
Try this:
Html:
<button id="search-btn" "class="uk-button uk-position-bottom" onclick="toggleSearch()">Start search</button>
JS:
var searching = false;
function toggleSearch(){
if(searching){
search.stop();
document.getelementbyid("search-btn").innerHTML = "Start search";
}else{
search.start();
document.getelementbyid("search-btn").innerHTML = "Stop search";
}
searching = !searching;
}
If I understood correctly your question this will solve your problem:
<button class="uk-button uk-position-bottom" data-process="0">Start search</button>
<script>
$(".uk-button").click(function () {
var $this = $(this);
var processStatus = $this.data("process");
//var search = new SiteSearch();
if (processStatus == "0") {
//you can trigger start function
$this.data("process", "1");
$this.text("Stop Search");
}
else if (processStatus == "1") {
//you can trigger stop function
$this.data("process", "0");
$this.text("Start Search");
}
});
</script>

onscroll div in a JavaScript object

i want to build a div with scroll, that when you scroll this div, it will active anothe function.
i need to build this in a Object.
there is any way to do this?
i write here an example source (that not work) of what i want.
<script type="text/javascript">
function onsc(divName, divChange) {
this.play = function() {
window.onload = function() {
document.getElementById(divName).onscroll = function() {
this.scroll(n)
}
};
}
this.scroll = function(n) {
document.getElementById(divChange).innerHTML = "you scroll!";
}
}
c[1] = new onsc("div1", "div1_i").play();
</script>
<div id="div1_i">this div will change when you scroll</div>
<div id="div1" style="background:#C6E2FF; width:300px; height:200px; overflow-y:scroll;">
<p style="height:800px;">txt</p>
</div>
Your code was nearly there. I made a few changes and put into a JSFiddle for you.
I added comments at what you missed. Most importantly the context of this changes when you entered into that function on the onscroll event.
JavaScript
function onsc(divName, divChange) {
// First of all make `this` inherit to below functions
var self = this;
this.play = function () {
document.getElementById(divName).onscroll = function() {
// Changed this to call the parent and place the correct DIV
self.scroll(divChange)
}
}
this.scroll = function (n) {
document.getElementById(divChange).innerHTML = "you scroll!";
}
}
c = new onsc("div1", "div1_i").play();
Demo
Have a look at my JSFiddle: http://jsfiddle.net/bJD8w/2/

onClick not waiting for a Click Javascript

I made a button that is supposed to start changing the color of some text every couple of seconds. The code DOES change color, but it happens right when the page is loaded, and doesn't wait for the user to click the button for it to change color. Here is my code. Please explain to me and show me how to make the code only execute when the user clicks the button.
<!DOCTYPE html>
<body>
<style>
#woo{
color: green;
}
#woot{
color: orange;
}
</style>
<button onClick="onChange()">SWAG</button>
<p id="woo">WAM</p>
<script>
setInterval(function(){onChange()}, 2000);
function onChange(){
document.getElementById("woo").id = "woot";
setTimeout(function(){
document.getElementById("woot").id = "woo";
}, 1000);
}
</script>
</body>
</html>
If you can help answer my question, please do.
As soon as you call setInterval() you ask the browser to execute onChange() every 2 seconds, regardless of the button.
Try something like:
<style>
#woo.green {
color: green;
}
#woo.orange {
color: orange;
}
</style>
<button onClick="startChange()">SWAG</button>
<p id="woo" class="orange">WAM</p>
<script>
var intervalRef;
var green = false;
function startChange() {
intervalRef = setInterval(function() { doChange(); }, 1000);
}
function stopChange() {
clearInterval(intervalRef);
}
function doChange() {
var el = document.getElementById("woo");
if (green) {
el.className = "orange";
green = false;
} else {
el.className = "green";
green = true;
}
}
</script>
All you need to do is remove the call to setInterval. Your onclick handler is fine. See this example, where I deleted the setInterval call:
http://jsfiddle.net/U6Z8F/

Categories