So i'm thinking to changing innerHTML of <p>Click</p> from content of "Click" into "Clicked" and when being clicked again it changes back again to "Click" (and could be clicked back again to result "Clicked" for endless times).
Can someone give clue? *I appreciate,
This is my fail attempt so far -->
<!DOCTYPE html>
<body>
<p id="event_01">Click</p>
<script>
let goo = document.querySelector("#event_01");
let clickOnce = function() {goo.innerHTML = "Clicked"};
let clickBack = function(){
goo.innerHTML = "Click"};
if(goo.textContent == "Click") {
goo.addEventListener("click", clickOnce);
} else if (goo.textContent == "Clicked") {
goo.addEventListener("click", clickBack);
}
</script>
</body>
You should put your condition inside a click handler instead of outside. What's between the script tag will only execute once. When the code runs (on page load) the content of goo is Click, so only the listener that sets the content to "clicked" ever gets attached to the element. instead you should do somthing like this:
let goo = document.querySelector("#event_01");
let onClick = function() {
if(goo.textContent == "Click"){
goo.innerHTML = "Clicked";
} else {
goo.innerHTML = "Click";
}
};
goo.addEventListener("click", clickOnce);
You just need to check the value of the .innerHTML of the <p></p>, compare it to the current .innerHTML and change it accordingly
<!DOCTYPE html>
<body>
<p id="event_01" onClick="myFunction()">Click</p>
<script>
function myFunction() {
var x = document.getElementById("event_01");
if (x.innerHTML === "Click") {
x.innerHTML = "Clicked";
} else {
x.innerHTML = "Click";
}
}
</script>
</body>
You just need one listener, attached from the beginning:
let goo = document.querySelector("#event_01");
goo.addEventListener("click", clickListener);
let clickListener = function() {
if (goo.innerHTML == "<p>Click</p>")
goo.innerHTML = "<p>Clicked</p>";
else
goo.innerHTML = "<p>Click</p>";
}
This is simple. your adding to much code.
first of when the p is clicked you assign a click event to clickOnce but in clickOnce
back you never assign clickBack.
Here is an example about what you want to do.
let goo = document.querySelector("#event_01");
let clickMe = function() {
if(goo.textContent == "Click")
{
goo.innerHTML = "Clicked";
}
else
{
goo.innerHTML = "Click";
}
}
goo.addEventListener("click", clickMe);
<p id="event_01">Click</p>
If you don't want to use functions or variables, you can use e.target.textContent
<!DOCTYPE html>
<body>
<p id="event_01">Click</p>
<script>
document.querySelector("#event_01").addEventListener('click', (e) => {
if (e.target.textContent === 'Click') {
e.target.textContent = 'Clicked'
} else if (e.target.textContent === 'Clicked') {
e.target.textContent = 'Click'
}
})
</script>
</body>
Related
I need to change text each time I click on button.
var button = document.getElementById("changeText");
button.addEventListener(
"click",
function () {
if (button.getAttribute("data-text") == button.innerHTML) {
button.innerHTML = button.getAttribute("data-text1");
} else {
button.setAttribute("data-text1", button.innerHTML);
button.innerHTML = button.getAttribute("data-text");
}
},
false
);
<div>
<button id="changeText" data-text="Show" data-text1="Hide">Hide</button>
</div>
I don't understand why this code doesn't work when I try to load page using google chrome. However when I loaded it to codepen it worked
It expects from you certain structure like this one:
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<div>
<button id="changeText" text="Show" >Hide</button>
</div>
<script>
var button = document.getElementById("changeText");
button.addEventListener(
"click",
function () {
if (button.getAttribute("text") == button.innerHTML) {
button.innerHTML = button.getAttribute("text1");
} else {
button.setAttribute("text1", button.innerHTML);
button.innerHTML = button.getAttribute("text");
}
},
false
);
</script>
</body>
</html>
Copy paste it to your file and you'll see that it works.
Please mark it as an answer if it fixes your problem :)
Your code is working, but your approach is not so nice. See the 2 options down below.
let text = {
'Hide': 'Show',
'Show': 'Hide'
}
const click = (event) => {
// option 1, it needs the object above.
// It's good for multiple alternatiosn like color, icon etc
// or multiple states like hide to show, show to sure, sure to really, really to hide.
event.target.innerText = text[event.target.innerText];
// option 2, it's good for one or two alternations.
// event.target.innerText = event.target.innerText == 'Hide' ? 'Show' : 'Hide'
}
document.querySelector('button').addEventListener('click', click);
<button>Show</button>
you can make it more simple by removing the custom attribute and use the button innerHTML only along with enum by using Object.freeze(),it will make the code more readable
const titleEnum = Object.freeze({show: "SHOW", hide: "HIDE"});
var button = document.getElementById("changeText");
button.addEventListener(
"click",
function () {
if (button.innerHTML === titleEnum.hide) {
button.innerHTML = titleEnum.show;
} else {
button.innerHTML = titleEnum.hide;
}
},
false
);
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<div>
<button id="changeText">HIDE</button>
</div>
</body>
</html>
Use innerText to get the value of an element
const changeBtn = document.getElementById("changeText");
changeBtn.addEventListener("click", ()=>{
if(changeBtn.innerText === "2"){
changeBtn.innerText = "1";
}
else{
changeBtn.innerText= "2";
}
});
<div>
<button id="changeText">1</button>
</div>
So for a website I have a feature where If you click an image it shows it in a lightbox then on the second click it tracks the mouse movement to move the image. That works fine the problem is on the third click I want to toggle the mouse tracking on and off.
I've posted a simplified version of the code with a button instead of an image
<body>
<div id="myDIV"></p>
<button style="padding: 30px;" id="myBtn">Try it</button>
</div>
<p id="demo"></p>
<script>
document.addEventListener('click', buttonClick);
let scrollon =false;
function buttonClick(event) {
var elem = event.target,
elemID = elem.getAttribute('id'),
myBtn = document.getElementById('myBtn');
if (elemID == 'myBtn' && !scrollon){
event.preventDefault();
scrollon=true;
mine();
console.log('triggered')
}else
if (elemID == 'myBtn' && scrollon){
event.preventDefault();
scrollon=false;
mine();
console.log('untriggered')
}
}
function mine(){
if (scrollon == false){
myBtn.removeEventListener('mousemove',scroll);
return;
}
myBtn.addEventListener('mousemove',scroll);
function scroll(e){
document.getElementById("demo").innerHTML = Math.random(); //keeps going
//do something
}
}
</script>
This is a very good alternative code which works perfectly fine and is used very often.
So I only changed the mine() function.
function mine() {
if (scrollon == false) {
myBtn.onmousemove = null;
} else {
myBtn.onmousemove = function (e) {
document.getElementById("demo").innerHTML = Math.random(); //keeps going
//do something
};
}
}
Hope I could help!
everyone. I got some problems when I wanna accomplish a drop-down box in a HTML website without using select and option elements, instead of using and elements.
The main function is made up by two parts, the first function is when clicked the first elements in the drop-down box, the hidden parts of list shows up and hide clicked again. The second function is when choose the elements in the hidden list, the text of the elements on the list will replace the first element on the drop-down box.
I have accomplished first function using below codes:
// javascript codes
var searchListBtn = document.getElementById("btn_List");
var a_searchListBtn = document.getElementById("btn_List").getElementsByTagName("a");
function show(event) {
let oevent = event || window.event;
if (document.all) {
oevent.cancelBubble = true;
}
else {
oevent.stopPropagation();
}
// click it to show it, click again to hide it and loop
if (searchListBtn.style.display === "none" || searchListBtn.style.display === "") {
searchListBtn.style.display = "block";
}
else {
searchListBtn.style.display = "none";
}
}
document.onclick = function() {
searchListBtn.style.display = "none";
}
searchListBtn.onclick = function (event) {
let oevent = event || window.event;
oevent.stopPropagation();
}
<!-- html codes -->
<html>
<body>
<div>
<div class="ui-search-selected" onclick="show();">A</div>
<div class="ui-search-selected-list" id="btn_List">
B
C
D
</div>
</div>
</body>
</html>
But when I did the second part, my idea was not clear enough to implement that, I searched if I use select>option elements I could use selectedIndex method to find the index of list, but this is a custom drop-down box formed by div>a structure elements.
I tried to console.log(a_searchListBtn) and show an array from the console, and I could use a_searchListBtn[0~3].text to get the value of B/C/D.
I tried to write codes like below:
a_searchListBtn.onclick = function() {
console.log("Clicked.")
}
But nothing in the console, so, is there anyone could apply some help, thx in advance.
Well you're fetching all the a elements using getElementsByTagName("a"). Now you just need to loop through the results and add a click event listener that will take the innerHTML of that a element and put it into the innerHTML of the ui-search-selected div.
You don't need an index. You can access the clicked element's innerHTML using event.target. See it working in this snippet below:
// javascript codes
var searchListBtn = document.getElementById("btn_List");
var uiSearchSelected = document.getElementById("ui-search-selected");
var a_searchListBtn = document.getElementById("btn_List").getElementsByTagName("a");
for (button of a_searchListBtn) {
button.addEventListener("click", replace);
}
function show(event) {
let oevent = event || window.event;
if (document.all) {
oevent.cancelBubble = true;
}
else {
oevent.stopPropagation();
}
// click it to show it, click again to hide it and loop
if (searchListBtn.style.display === "none" || searchListBtn.style.display === "") {
searchListBtn.style.display = "block";
}
else {
searchListBtn.style.display = "none";
}
}
document.onclick = function() {
searchListBtn.style.display = "none";
}
searchListBtn.onclick = function (event) {
let oevent = event || window.event;
oevent.stopPropagation();
}
function replace(event) {
if (!event) return;
uiSearchSelected.innerHTML = event.target.innerHTML
}
<!-- html codes -->
<html>
<body>
<div>
<div id="ui-search-selected" onclick="show();">A</div>
<div class="ui-search-selected-list" id="btn_List">
B
C
D
</div>
</div>
</body>
</html>
I have tried to use this codes to implement this funtion, it works.
// javascript
var par_searchListBtn = document.getElementById("btn_list_parent");
var searchListBtn = document.getElementById("btn_List");
var a_searchListBtn = document.getElementById("btn_List").getElementsByTagName("a");
// console.log(a_searchListBtn.length);
// console.log(a_searchListBtn);
function show(event) {
let oevent = event || window.event;
if (document.all) {
oevent.cancelBubble = true;
}
else {
oevent.stopPropagation();
}
if (searchListBtn.style.display === "none" || searchListBtn.style.display === "") {
searchListBtn.style.display = "block";
}
else {
searchListBtn.style.display = "none";
}
}
document.onclick = function() {
searchListBtn.style.display = "none";
}
searchListBtn.onclick = function (event) {
let oevent = event || window.event;
oevent.stopPropagation();
}
for(var i = 0; i < a_searchListBtn.length; i++){
a_searchListBtn[i].onclick = function () {
par_searchListBtn.innerHTML = this.innerText;
//searchListBtn.style.display = "none";
}
}
<!-- html codes -->
<html>
<body>
<div>
<div class="ui-search-selected" id="btn_list_parent" onclick="show();">A</div>
<div class="ui-search-selected-list" id="btn_List">
B
C
D
</div>
</div>
</body>
</html>
I am seeing how I can make an Are You Human checkbox, but I am having a problem (Code At The End). I am trying to make it see if it is clicked until it is clicked. I tried onclick, but that is not working.
window.onload = function() {
var input = document.getElementById('ruhuman');
function check() {
if (input.checked) {
ruhuman.checked = true;
if (event.originalEvent === undefined) {
ruhuman.human = false;
} else {
ruhuman.human = true;
}
}
alert(ruhuman.human);
alert(ruhuman.checked);
}
input.onchange = check;
check();
}
<input type="checkbox" id="ruhuman" class="ruhuman" onclick="check()" required="required">
<label>R U Human?</label>
Edit: Thanks for your help! Finished product at http://ruhuman.github.io/.
To the people that answered I can put your github for your help!
originalEvent is JQuery, not JavaScript. A workaround is to test screenX and screenY -- if it's a human, these will have some value based on the checkbox position. Also, you can remove the onclick from your html and tie your click event like this:
document.getElementById ("ruhuman").addEventListener("click", function(e){
if (this.checked) {
ruhuman.checked = true;
if (e.screenX && e.screenY) {
ruhuman.human = true;
} else {
ruhuman.human = false;
}
}
console.log(ruhuman.human);
console.log(ruhuman.checked);
});
JS Fiddle Demo
This works: https://jsfiddle.net/rz4pmp5L/3/
var input = document.getElementById('ruhuman');
var ruhuman =
{
checked: false
};
function check()
{
if (input.checked)
{
ruhuman.checked = true;
}
alert(ruhuman.checked);
}
input.onchange = check;
check();
The problem was (at least) that ruhuman was not defined at all.
I have a Javascript block of code but I don't know how to activate it.
I would like it to be activated with a HTML button but I don't know if it's possible. I'm just beginning in coding =P
Here's the code:
var randomFlavour = Math.random() * 10;
if (randomFlavour < 1) {
var randomFlavour = "chocolate";
} else if (randomFlavour < 2) {
var randomFlavour = "vanilla";
} else if (randomFlavour < 3) {
var randomFlavour = "pistachio";
} else if (randomFlavour < 4) {
var randomFlavour = "strawberry";
} else if (randomFlavour < 5) {
var randomFlavour = "cotton candy";
} else if (randomFlavour < 6) {
var randomFlavour = "cookie dough";
} else if (randomFlavour < 7) {
var randomFlavour = "bubblegum";
} else if (randomFlavour < 8) {
var randomFlavour = "peanut butter";
} else if (randomFlavour < 9) {
var randomFlavour = "mint";
} else {
var randomFlavour = "gingerbread man";
}
console.log("Hello. I would like to have" + " " + randomFlavour + " " + "ice cream please.");
A cleaner way might be to do something like this:
flavors = [
'strawberry',
'apple'];
function getRandomFlavor()
{
random_index = Math.floor(Math.random() * flavors.length);
return flavors[random_index];
}
console.log(getRandomFlavor());
http://jsfiddle.net/Bm345/1/
To execute a function when a button is clicked, you first need a button:
HTML:
<button type="button">Click this button!</button>
Then you need to attach an event listener to the button. For beginners you will often be shown how to do this inline with an [onclick] attribute, but it's absolutely terrible practice and not a good habit to be in. If you were to add an event handler inline, you'd have to update all of them every time you wanted to do something as simple as change the event handler name. This is tedious and terrible for maintenance.
It's much easier long-term to bind events via JavaScript. You can do this a few different ways. The best is with addEventListener (or a library that makes use of addEventListener, such as with jQuery.fn.on):
JS:
//this line of code tells the `buttonVariable` element to call the
//`callbackFunction` when the button is clicked
buttonVariable.addEventListener('click', callbackFunction, false);
Another way is to use the onclick property:
buttonVariable.onclick = callbackFunction;
For that code to work, you need to have selected the <button> element, and created a callbackFunction function:
//declare the variable
var buttonVariable;
//declare the function
function callbackFunction () {
...do stuff...
}
//select the button
buttonVariable = document.querySelector('button');
//bind the function to the button for click events
buttonVariable.addEventListener('click', callbackFunction, false);
It's also important to note that the script must execute after the <button> has been added to the DOM. JavaScript scripts are executed synchronously:
<script>
var btn;
//this returns null because the script executes before
//the button element exists
btn = document.querySelector('button');
</script>
<button type="button">Click this button!</button>
<script>
var btn;
//this returns an HTMLButtonElement object
btn = document.querySelector('button');
</script>
Here's a working example on jsfiddle.
Wrap your js code in a function. Set the onclick listener of the button to call your function.
<html>
<head>
<script>
function myFunction() {
... all of your javascript code ...
}
</script>
</head>
<body>
<button onclick="myFunction()">My Button</button>
</body>
</html>