I am trying to make a calendar web application and want to save a users' state using localstorage. I have tried using two methods (innerHTML as well as a javascript DOM-to-JSON; https://github.com/azaslavsky/domJSON), but each removes the button's onclick event.
I believe the problem is that it is stringifying only the innerhtml, which for some reason doesnt have my onlick event listed (although the onlick event fires). What should I do so that a user can reload the page and still use the buttons.
Here is an example that shows the button stop working (delete cache and website cookies/data to make the button work again):
https://codepen.io/samuel-solomon/pen/XWdzKjd?editors=1011
window.pageState;
$(document).ready(function(){
let div = document.getElementById("div")
window.pageState = JSON.parse(localStorage.getItem('pageState'));
if (window.pageState === null) {
let btn = document.createElement('button')
btn.innerText = "Hello";
btn.style = "height: 100px";
btn.onclick = function (btn) {change_text(btn)}.bind(null, btn);
div.appendChild(btn);
window.pageState = {state: div.innerHTML};
}
else {div.innerHTML = window.pageState.state}
});
function change_text(btn) {
let div = document.getElementById("div");
if (btn.innerText === "Hello") {btn.innerText = "Goodbye";}
else if (btn.innerText === "Goodbye") {btn.innerText = "Hello";}
localStorage.setItem('pageState', JSON.stringify(window.pageState));
}
Here is my wbesite where the problem exists (Ex: double click 'Ae 101A' and double click it in the calender. it should disappear. Now add it again and reload the page. Now it doesnt disappear on double click):
https://turtle-pond.com/
It seems you are using jQuery. For hooking events to dynamically created elements, I suggest the selector filtering approach: instead of binding the click event on the button element itself, listen for the click event on the parent container (or even the document) and filter by the button's selector. Here is how:
window.pageState;
$(document).ready(function(){
let div = document.getElementById("div")
$(document).on('click', "#my-button", function (event) {
const btn = event.target; // or btn = document.getElementById("my-button");
change_text(btn);
});
window.pageState = JSON.parse(localStorage.getItem('pageState'));
if (window.pageState === null) {
let btn = document.createElement('button')
btn.innerText = "Hello";
btn.style = "height: 100px";
btn.id = "my-button";
div.appendChild(btn);
window.pageState = {state: div.innerHTML};
}
else {div.innerHTML = window.pageState.state}
});
function change_text(btn) {
let div = document.getElementById("div");
if (btn.innerText === "Hello") {btn.innerText = "Goodbye";}
else if (btn.innerText === "Goodbye") {btn.innerText = "Hello";}
localStorage.setItem('pageState', JSON.stringify(window.pageState));
}
Read more about this on jQuery documentation and here.
Related
The idea that the user writes a todo, and I will be displayed in a div, if you click at the div the writing will be strikes through, but if you hover will be a small div with a trash icon displayed. My problem is that every time I click on the child element the written part of the parent div will be striked through. How can I prevent the child from acting the same as the parent? I write event.stopPropagation(); but doesn't work.
let text_field = document.getElementById("fname");
let count = 0;
text_field.addEventListener("keypress", function(event) {
if(event.key === "Enter") {
count++;
console.log(count);
event.preventDefault();
let block_to_insert = document.createElement('div');
block_to_insert.id = "div-created"+count+"";
let text_to_insert = document.getElementById('fname').value;
let text=block_to_insert.innerHTML = ''+text_field.value;
block_to_insert.classList.add('todo-div-todo');
let where_to_insert = document.getElementById('outer-div');
where_to_insert.appendChild( block_to_insert );
block_to_insert.onclick = function(e){
block_to_insert.style.setProperty("text-decoration", "line-through");
}
block_to_insert.onmouseover = function(){
let delete_div = document.createElement('div');
let text=delete_div.innerHTML = '<i class="fa-solid fa-trash" style="color:white"></i>';
delete_div.classList.add('delete-todo');
delete_div.id = "delete-div"+count+"";
let place_to_insert = document.getElementById(block_to_insert.id);
place_to_insert.appendChild( delete_div );
document.getElementById("delete-div"+count+"").addEventListener('click',function (event){
event.stopPropagation();
event.preventDefault();
},true);
}
}
});
I am working on follow button and with the help of JavaScript I've come up with the following code.
But the problem is I have to double click the follow button to functioning this is due to using click event 2 time. I am open to better methods of solving this too.
var value = null;
const onClick = (event) => {
// event.target.id
value = event.target.id;
console.log(value);
document.getElementById(`${value}`).addEventListener('click',function(){
// console.log(value.id);
if(this.classList.contains('follow')){
this.classList.remove('follow');
this.innerHTML ="Following";
this.style.backgroundColor = 'green' ;
}else{
this.classList.add('follow');
this.style.backgroundColor = 'rgb(27,18,83)' ;
this.innerHTML="Follow";
}
})
}
window.addEventListener('click', onClick);
There is a double click event. You can check the if it satisfies your requirement.
MDN link - https://developer.mozilla.org/en-US/docs/Web/API/Element/dblclick_event
For multiple buttons with the same function, I would give all of them the same class (e.g. "btn"). Then in JS simply get all of the elements with this class, loop over the HTMLCollection which you would get and assign each element an eventlistener. When you want to change something on the button you have to use event.target in the function:
let buttons = document.getElementsByClassName("btn");
for (btn of buttons) {
btn.addEventListener("click", (event) => {
if(event.target.classList.contains('follow')){
event.target.classList.remove('follow');
event.target.innerHTML ="Following";
event.target.style.backgroundColor = 'green' ;
}else{
event.target.classList.add('follow');
event.target.style.backgroundColor = 'rgb(27,18,83)' ;
event.target.innerHTML="Follow";
}
});
}
<button class="btn">1</button>
<button class="btn">2</button>
I’m new to Js.. and I’m trying to change the inner Text of a button to toggle on click between On and Off using addEventListener method.
const btn = document.getElementsByClassName("btn")[0];
const btn2 = document.createTextNode("Off");
btn.addEventListener.toggle("click", modifiedText() {
// enter code here
});
ModifiedText() {
// enter code here
}
<button class=“btn”>On</button>
Just addEventListener on button and get or set the text inside button using textContent property.
const button = document.querySelector(".btn");
button.addEventListener("click", function clickHandler( e ) {
const btnText = e.target.textContent;
if( btnText.toLowerCase() === "on") e.target.textContent = "Off";
else e.target.textContent = "On"
})
<button class="btn">On</button>
all
I am currently practicing my coding skills and am making a simple footer selection webpage.
I have four footers with different looks that are set to "display:none" initially. Then, I have four buttons, each one corresponding to its footer type. When the button is clicked, it displays the footer.
Now I just want to know how do I write a cleaner Javascript than what I currently have. Thank you as always.
var footer1 = document.getElementById('footer1');
var footer2 = document.getElementById('footer2');
var footer3 = document.getElementById('footer3');
var footer4 = document.getElementById('footer4');
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
var btn3 = document.getElementById('btn3');
var btn4 = document.getElementById('btn4');
btn1.onclick = function(e) {
console.log('You clicked button1');
e.preventDefault();
footer1.style.display = 'block';
footer2.style.display = 'none';
footer3.style.display = 'none';
footer4.style.display = 'none';
}
btn2.onclick = function(e) {
console.log('You clicked button2');
e.preventDefault();
footer2.style.display = 'block';
footer1.style.display = 'none';
footer3.style.display = 'none';
footer4.style.display = 'none';
}
btn3.onclick = function(e) {
console.log('You clicked button3');
e.preventDefault();
footer3.style.display = 'block';
footer2.style.display = 'none';
footer1.style.display = 'none';
footer4.style.display = 'none';
}
btn4.onclick = function(e) {
console.log('You clicked button4');
e.preventDefault();
footer4.style.display = 'block';
footer2.style.display = 'none';
footer3.style.display = 'none';
footer1.style.display = 'none';
}
You can just use Arrays like this:
let buttons = [ 'btn1', 'btn2', 'btn3', 'btn4' ];
let footers = [ 'footer1', 'footer2', 'footer3', 'footer4' ];
buttons.forEach((btn, index) => {
// Please note that you might want to use addEventListener instead of onclick
document.getElementById(btn).addEventListener('click', (event) => {
event.preventDefault();
let button = 'button' + (index + 1);
alert('You clicked ' + button);
footers.forEach((footer, index_f) => {
let f = document.getElementById(footer);
if(index_f === index) {
f.style.display = 'block';
}
else {
f.style.display = 'none';
}
});
});
});
To make things even more interesting, you can play with querySelectorAll and custom attributes. You could, for example, add the classes custom-button to your buttons and custom-footer to your footers, and on each button add a data-footer attribute pointing to the id of the corresponding footer. Then, you could do this:
document.querySelectorAll(".custom-button").forEach((button) => {
button.addEventListener('click', (event) => {
document.querySelectorAll(".custom-footer").forEach(footer => footer.style.display = 'none');
let footer = button.getAttribute("data-footer");
document.getElementById(footer).style.display = 'block';
});
});
Quite shorter.
There is a common way to do this.
Share a class (foo) between all of the elements you want to group into your show/hide radio button-like functionality.
Then use one function, like
function handler = function(e) {
var foos = document.getElementsByClass("foo");
// make all foos display="none"
var target = targets[e.target]; //get the footer to show from the target button
target.style.display = "block";
}
You can use attribute selector to loop over elements.
[attributeName="value"]
^: Means starts with
$: Ends with
This way, your logic is generic and does not requires you to maintain any list of IDs
Idea:
You can create a pattern where every button id will correspond to visibility to necessary footer. Better idea would be to use data attribute(data-<attr name>) but you can work with ids for now.
Loop over all the buttons and add handler using addEventListener. onClick is a property, so assignment will erase/ override previous value. You can either have inline anonymous function or a named function if you have too many buttons.
In this handler, loop over all footers and hide them.
Fetch index using this.id and show necessary footer. Its always better to use classes for such actions instead of setting styles.
var buttons = document.querySelectorAll('[id^="btn"]');
Array.from(buttons, (button) => {
button.addEventListener('click', function(event) {
const footers = document.querySelectorAll('[id^="footer"]');
Array.from(footers, (footer) => footer.style.display = 'none' );
const index = this.id.match(/\d+/)[0];
document.getElementById(`footer${index}`).style.display = 'block';
})
})
div[id^="footer"] {
width: 100px;
height: 100px;
border: 1px solid gray;
margin: 10px;
}
<div id="footer1"> Footer 1 </div>
<div id="footer2"> Footer 2 </div>
<div id="footer3"> Footer 3 </div>
<div id="footer4"> Footer 4 </div>
<button id="btn1"> Button 1 </button>
<button id="btn2"> Button 2 </button>
<button id="btn3"> Button 3 </button>
<button id="btn4"> Button 4 </button>
References:
Attribute Selector - MDN
I'm currently studying a full stack course and my modal isn't behaving as expected
I'm a bit lost on what to do as I can't find any documentation anywhere and while clicking on the close button or pressing ESC works, clicking outside of the box doesn't.
The following code is how it has been suggested I approach the issue but, it doesn't work. I've honestly stared at this for about an hour and just can't connect the dots on what is (not) happening? Please excuse all the commenting and additional code as I'm still learning so, it's how I'm able to follow what's going on:
function showModal() {
var $modalContainer = document.querySelector('#modal-container');
$modalContainer.classList.add('is-visible');
}
function hideModal() {
var $modalContainer = document.querySelector('#modal-container');
$modalContainer.classList.remove('is-visible');
}
//modal IFFE
document.querySelector('#modal-button').addEventListener('click', () => {
showModal();
});
//-- show modal --
function showModal(title, text) {
var $modalContainer = document.querySelector('#modal-container');
//Selects the element with the associated id
// Clear all content for the selected element
$modalContainer.innerHTML = '';
var modal = document.createElement('div'); //creates a div element withing selected element
modal.classList.add('modal'); //assigns new class to the div element
// Add the new modal content
var closeButtonElement = document.createElement('button'); //creates the close button
closeButtonElement.classList.add('modal-close'); //assigns a class to the new (close) button
closeButtonElement.innerHTML = "×"; //inserts text within the new(close) button
closeButtonElement.addEventListener('click', hideModal);
var titleElement = document.createElement('h1');
titleElement.innerText = title;
var contentElement = document.createElement('p');
contentElement.innerText = text;
modal.appendChild(closeButtonElement);
modal.appendChild(titleElement);
modal.appendChild(contentElement);
$modalContainer.appendChild(modal);
$modalContainer.classList.add('is-visible');
}
document.querySelector('#modal-button').addEventListener('click', () => {
showModal('PokéMon', 'Here is all of the info about your PokéMon');
});
window.addEventListener('keydown', (e) => {
var $modalContainer = document.querySelector('#modal-container');
if (e.key === 'Escape' && $modalContainer.classList.contains('is-
visible')) {
hideModal();
}
});
$modalContainer.addEventListener('click', (e) => {
var target = e.target;
if (target === $modalContainer) {
hideModal();
}
});
Expected result: User clicks outside of the modal (on the container) and the modal closed.
Current result: No change in state, modal remains active and visible. Only by clicking on the close button (x) or by pressing ESC is the desired result achievable.
By Looking at this code I am not sure what is actually supposed to make the modal visible or hide it. Without access to your css (if you have any). I am assuming that all you are doing is adding and removing the class .is-visible from the #modal-container element.
I would suggest that you apply this class to the modal itself, and then you could toggle this class on and off,
Modify your code to do this by doing something like this (added on top of your code):
function showModal() {
var $modalContainer = document.querySelector('#modal-container');
$modalContainer.classList.add('is-visible');
document.querySelector('.modal').classList.remove('hide-el')
}
function hideModal() {
var $modalContainer = document.querySelector('#modal-container');
$modalContainer.classList.remove('is-visible');
document.querySelector('.modal').classList.add('hide-el')
}
Where hide-el in your css is:
.hide-el {
display: none;
}
You could also modify your code to appply the is-visible class to your modal element. You should always try to attach the class/id to the element you want to manipulate if you have that option.
Or if you do not have access to a css file:
document.querySelector('.modal').style.display = "none"
and
document.querySelector('.modal').style.display = "block"
Also, your code seems very verbose, was this boilerplate part of the assignment?
heres a working example: https://codepen.io/mujakovic/pen/zVJRKG
The code was in the incorrect place in the end and should have looked something like this:
modal.appendChild(closeButtonElement);
modal.appendChild(titleElement);
modal.appendChild(contentImage);
modal.appendChild(contentHeight);
modal.appendChild(contentElement);
$modalContainer.appendChild(modal);
$modalContainer.classList.add('is-visible');
$modalContainer.addEventListener('click', (e) => { //listening for an event (click) anywhere on the modalContainer
var target = e.target;
console.log(e.target)
if (target === $modalContainer) {
hideModal();
}
});
};
window.addEventListener('keydown', (e) => { //listening for an event (ESC) of the browser window
var $modalContainer = document.querySelector('#modal-container');
if (e.key === 'Escape' && $modalContainer.classList.contains('is-visible')) {
hideModal();
}
});
This is because the action was originally being called on page load and targeted within the window instead of being called within the container and being loaded when the modal loads.
Thank for your help