Pass ID from one html element to another with JavaScript - javascript

my problem is pretty simple. I'm trying to switch 2 elements id by clicking either of them using only vanilla JavaScript.
It works on the first click to use the correct CSS for the new id, but afterward, it does not seem to recognize click events to the new id. Here is a short code example to illustrate this:
document.addEventListener("DOMContentLoaded", function(){
var blueSpin = document.getElementById("blue-spinner");
var orangeSpin = document.getElementById("orange-spinner");
blueSpin.addEventListener("click", function() {
document.getElementById("h1").innerHTML = "You've Clicked Blue";
blueSpin.setAttribute("id","orange-spinner");
orangeSpin.setAttribute("id", "blue-spinner")
});
orangeSpin.addEventListener("click", function() {
document.getElementById("h1").innerHTML = "You've Clicked Orange";
orangeSpin.setAttribute("id", "blue-spinner");
blueSpin.setAttribute("id", "orange-spinner");
});
});
h1, h2 {
font-weight: bold;
text-align: center;
font-size: 45px;
font-family: 'VT323', monospace;
margin: 15px;
}
#blue-spinner {
color: blue;
}
#orange-spinner {
color: goldenrod;
}
<script src="https://use.fontawesome.com/releases/v5.0.2/js/all.js"></script>
<html>
<body>
<h1 id="h1">Click Something:</h1>
<h2 id="blue-spinner"><i class="fa fa-cubes fa-spin" aria-hidden="true"></i></h2>
<h2 id="orange-spinner"><i class="fa fa-cubes fa-spin" aria-hidden="true"></i></h2>
</body>
</html>
My expectation is that upon clicking either spinner, the colors will switch, and the header will identify which one was clicked before the change. After that, you should be able to click either of the spinners with the same result.
Any help anyone can provide would be appreciated! Happy X-mas Eve Eve!

I would use class selectors in css instead of id. Something along these lines:
var btns = document.getElementsByClassName("btn");
for(var i = 0; i < btns.length; i++){
btns[i].addEventListener("click", function(e) {
var clss = e.target.getAttribute("class")
if(clss === undefined || cls === null){clss = "";}
if(cls.indexOf("blue-spinner") > -1){
var output = "You clicked a blue spinner";
e.target.setAttribute("class", "orange-spinner");
}else{
e.target.setAttribute("class", "blue-spinner");
var output = "You clicked an orange spinner";
}
var h = document.getElementById("h1");
h.innerHTML = output;
});
}

Since you change the id for the element you have to update your code after the change.
document.addEventListener("DOMContentLoaded", function() {
var blueSpin = document.getElementById("blue-spinner");
var orangeSpin = document.getElementById("orange-spinner");
var blueSpinClick = function() {
document.getElementById("h1").innerHTML = "You've Clicked Blue";
blueSpin.removeEventListener('click', blueSpinClick);
orangeSpin.removeEventListener('click', orangeSpinClick);
blueSpin.removeEventListener('click', blueSpinClick);
blueSpin.setAttribute("id","orange-spinner");
orangeSpin.setAttribute("id", "blue-spinner");
blueSpin = document.getElementById("blue-spinner");
orangeSpin = document.getElementById("orange-spinner");
blueSpin.addEventListener("click", blueSpinClick);
orangeSpin.addEventListener("click", orangeSpinClick);
}
document.getElementById("blue-spinner").addEventListener("click", blueSpinClick);
var orangeSpinClick = function() {
document.getElementById("h1").innerHTML = "You've Clicked Orange";
orangeSpin.removeEventListener('click', orangeSpinClick);
blueSpin.removeEventListener('click', blueSpinClick);
blueSpin.setAttribute("id","orange-spinner");
orangeSpin.setAttribute("id", "blue-spinner");
blueSpin = document.getElementById("blue-spinner");
orangeSpin = document.getElementById("orange-spinner");
blueSpin.addEventListener("click", blueSpinClick);
orangeSpin.addEventListener("click", orangeSpinClick);
}
document.getElementById("orange-spinner").addEventListener("click", orangeSpinClick);
});
h1, h2 {
font-weight: bold;
text-align: center;
font-size: 45px;
font-family: 'VT323', monospace;
margin: 15px;
}
#blue-spinner {
color: blue;
}
#orange-spinner {
color: goldenrod;
}
<script src="https://use.fontawesome.com/releases/v5.0.2/js/all.js"></script>
<html>
<body>
<h1 id="h1">Click Something:</h1>
<h2 id="blue-spinner"><i class="fa fa-cubes fa-spin" aria-hidden="true"></i></h2>
<h2 id="orange-spinner"><i class="fa fa-cubes fa-spin" aria-hidden="true"></i></h2>
</body>
</html>

Related

how to save toogle class with localstorage. so can someone check what's wrong with this code

if( localStorage.getItem("color") == "black" ) {
{
var element = document.getElementById("body");
element.classList.toggle("bdark");
}
{
var element = document.getElementById("theader");
element.classList.toggle("hdark");
}
{
var element = document.getElementById("sh");
element.classList.toggle("shh");
}
}
function myFunction() {
{
var element = document.getElementById("body");
element.classList.toggle("bdark");
}
{
var element = document.getElementById("theader");
element.classList.toggle("hdark");
}
{
var element = document.getElementById("sh");
element.classList.toggle("shh");
}
var hs = document.getElementById("hs");
var color;
if(localStorage.getItem("color") == "black") {
color = "black";
localStorage.setItem("color",color)
}
.bdark {
background-color: #333;
color: white;
}
.hdark {
background-color: black;
color: white;
}
.shh {
display: none;
}
.hs {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body id="body" class="light">
<p id="theader">Click the "Try it" button to toggle between adding and removing the "mystyle" class name of the DIV element:</p>
<button id="button" onclick="myFunction()">Try it</button>
<div id="aaas">
<div id="sh" class="sh">☾</div>
<div id="hs" class="hs">☀</div>
</div>
</body>
</html>
i want this code to onclick toggle class and when i refresh the page those toggled class remain same as they were before reloading the page with localstorage. so can someone check what's wrong with this code. help me with something similar/alternative to this one. thanks for reading this.
Details:-
i want this code to work as (onclick class change + saved with cokies/localstorage/or anything) so whenever i refresh or reopen the page it would be same class as it was when i left. or some alternative code that works same.
I fixed your code
if( localStorage.getItem("color") == "black" ) {
{
let element = document.getElementsByTagName("body");
element.classList.toggle("bdark");
}
{
let element = document.getElementById("theader");
element.classList.toggle("hdark");
}
{
let element = document.getElementById("sh");
element.classList.toggle("shh");
}
}
function myFunction() {
{
let element = document.getElementsByTagName("body");
element.classList="bdark";
}
{
let element = document.getElementById("theader");
element.classList="hdark";
}
{
let element = document.getElementById("sh");
element.classList="shh";
}
{
let hs = document.getElementById("hs");
}
let color;
if(localStorage.getItem("color") != "black") {
color = "black";
localStorage.setItem("color", color)
}
}
.bdark {
background-color: #333;
color: white;
}
.hdark {
background-color: black;
color: white;
}
.shh {
display: none;
}
.hs {
display: none;
}
<p id="theader">Click the "Try it" button to toggle between adding and removing the "mystyle" class name of the DIV element:</p>
<button id="button" onclick="myFunction()">Try it</button>
<div id="aaas">
<div id="sh" class="sh">☾</div>
<div id="hs" class="hs">☀</div>
</div>

How to toggle a button with JS

I have a button and it should increase the font size when clicked and if it's clicked again it should decrease the font. Also the value of the button should change to Increase Font / Decrease Font. So, basically I want to make the button toggle from increasing the font to 16px then decreasing to 14px if clicked again.
EDIT: I made it work but it doesn't keep repeating. Only works twice and that's it
HTML
<p id="increase">Lorem Ipsum.</p>
<input onclick="font()" style="background-color:#72cf26" type="submit" value="Increase Font" id = "fontbutton"/>
JS
function font(){
var fontsize = document.getElementById('increase');
var fontbutton = document.getElementById('fontbutton');
if (fontbutton.value == "Increase Font"){
fontsize.classList.add("font16");
document.getElementById('fontbutton').value = "Decrease Font";
}else if (fontbutton.value == "Decrease Font"){
fontsize.classList.add("font14");
document.getElementById('fontbutton').value = "Increase Font";
}
}
CS
.font16{
font-size:16px;
}
.font14{
font-size: 14px;
}
You should use fontbutton.value instead of fontbutton.getElementById.value and remove the previous class using fontsize.classList.remove to add the new one using fontsize.classList.add:
function font(){
var fontsize = document.getElementById('increase');
var fontbutton = document.getElementById('fontbutton');
if (fontbutton.value == "Increase Font"){
fontsize.classList.remove("font14");
fontsize.classList.add("font16");
fontbutton.value = "Decrease Font";
}else if (fontbutton.value == "Decrease Font"){
fontsize.classList.remove("font16");
fontsize.classList.add("font14");
fontbutton.value = "Increase Font";
}
}
.font16{
font-size:16px;
}
.font14{
font-size: 14px;
}
<p id="increase" class="font14">Lorem Ipsum.</p>
<input onclick="font()" style="background-color:#72cf26" type="submit" value="Increase Font" id = "fontbutton"/>
The above requirement can be implemented using
element.classlist.add and element.classlist.remove functions.
Here is a copy of the working code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.font16{
font-size:16px;
background-color:#72cf26;
}
.font14{
font-size: 14px;
background-color:#72cf26;
}
</style>
</head>
<body>
<p id="increase">Lorem Ipsum.</p>
<button id="fontbutton" class="font14" onclick="toggleFont()">
Increase Font
</button>
<script>
function toggleFont() {
var element = document.getElementById("fontbutton")
var buttonText = element.innerHTML
element.classList.remove("font14")
element.classList.remove("font16")
if(buttonText.indexOf("Increase") >= 0) {
element.classList.add("font16")
element.innerHTML = "Decrease font"
} else {
element.classList.add("font14")
element.innerHTML = "Increase font"
}
}
</script>
</body>
</html>
Output:
More information:
https://www.w3schools.com/howto/howto_js_toggle_class.asp
$(document).ready(function(){
var flag = true;
$('.btn').click(function(){
$(this).find('span').toggleClass('hidden');
if(flag) {
$('#increase').addClass('font16');
$('#increase').removeClass('font14');
flag = !flag;
}else {
$('#increase').removeClass('font16');
$('#increase').addClass('font14');
flag = !flag;
}
});
});
.font16{
font-size:16px;
}
.font14{
font-size: 14px;
}
.hidden {
display: none;
}
p{ font-size: 10px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="increase">Lorem Ipsum.</p>
<button class="btn">
<span>Increse Font</span>
<span class="hidden">Decrese Font</span>
</button>
Your approach is complicated, JS directly offers a toggle method to add / delete a class and which returns a boolean value.
The only difficulty is that you should not forget to add !important to upgrade the size.
const paragraphInc = document.getElementById('increase')
, buttonSize = document.getElementById('fontbutton')
;
buttonSize.onclick = () =>
{
buttonSize.textContent = (paragraphInc.classList.toggle('Size16'))
? 'Decrease Font'
: 'Increase Font'
}
#fontbutton {
background-color:#72cf26;
padding: 7px 12px;
}
#increase {
font-size: 14px;
}
.Size16 {
font-size: 16px !important;
}
<p id="increase">Lorem Ipsum.</p>
<button id="fontbutton">Increase Font</button>

Refreshing a page returns [object CSSStyleDeclaration]

When I edit a content and saved changes, it shows [object CSSStyleDeclaration] instead of my updated content when refreshing the page.
function newElement() {
let li = document.createElement("li");
let inputvalue = document.querySelector("#myInput").value;
let savedNote = document.createTextNode(inputvalue);
li.appendChild(savedNote);
if (inputvalue === '') {
alert("Please write something")
} else {
document.querySelector("#myNotes").appendChild(li);
}
document.querySelector("#myInput").value = '';
}
function saveEdits() {
let editElement = document.querySelector("#saved-notes");
editElement = document.querySelector("#myNotes");
let userVersion = editElement.innerHTML;
userVersion = editElement.style;
localStorage.userEdits = userVersion;
document.querySelector("#update").innerHTML = "Edits saved. Refresh the page to see changed content";
}
function checkEdits() {
if (localStorage.userEdits != null)
document.querySelector("#saved-notes").innerHTML = localStorage.userEdits;
document.querySelector("#myNotes").style = localStorage.userEdits;
}
ul {
margin: 0;
padding: 0;
}
ul li {
cursor: pointer;
position: relative;
padding: 12px 8px 12px 40px;
background: #eee;
font-size: 18px;
transition: 0.2s;
}
<html>
<head>
<meta charset="utf-8">
</head>
<body onload="checkEdits()">
<div id="myDiv" class="new-note">
<textarea id="myInput"></textarea><br>
<button onclick="newElement()" class="save-button">Create</button>
<button onclick="saveEdits()" class="edit-button">Save Changes</button>
</div>
<div id="update"></div>
<div id="saved-notes"></div>
<ul id="myNotes">
</ul>
</body>
</html>
It will work if I removed userVersion = editElement.style;, but there will no CSS style. Just plain text.
I want to understand why this happens and learn from it. Thanks in advance.
It's because the Function localStorage.set can only save Strings, so it will call .toString() on the Object before it get stored and the Result of it is it's type [object CSSStyleDeclaration]. Did you tried to stringify it before you safe it?
userVersion = JSON.stringify(editElement.style);
document.querySelector("#myNotes").style = JSON.parse(localStorage.userEdits);

Dynamic <a> not clickable

I have done the following code in php so that I can click on the arrow and a form opens below
echo '<div class="editor" id="'.$par_code.'" style=" background-color: #fdfdfd; padding:14px 25px 30px 20px; font-family: Lucida Console, Monaco, monospace; box-shadow: 0 1px 10px 2px rgba(0,0,0,0.2),0 8px 20px 0 rgba(0,0,0,0.03); border-radius: 3px;">'
.'<img width="50" height="50" style="border-radius:50%" src="images/default.png" alt="Image cannot be displayed"/>'
.'<p class="uname"> '.$uname.'</p> '
.'<p class="time">'.$date.'</p>'
.'<p class="comment-text" style="word-break: break-all;">'.$content.'</p>'
.'<a class="link-reply al" id="reply" name="'.$par_code.'" style="padding-top: 18px; float: right;"><i class="fa fa-reply fa-lg" title="Reply"></i></a>';
My javascript code:
$(document).ready(function() {
$("a#reply").one("click" , function() {
var comCode = $(this).attr("name");
var parent = $(this).parent();
var str1 = "new-reply";
var str2 = "tog";
var res = str1.concat(i);
var tes = str2.concat(i);
// Create a new editor inside the <div id="editor">, setting its value to html
parent.append("<br /><center><form action='index.php' method='post' id='"+tes+"'><input class='iptext2' type='text' name='uname2' id='uname2' placeholder='Your Name' required /><div style='padding-bottom:5px'></div><textarea class='ckeditor' name='editor' placeholder='Your Query' id='"+res+"' required></textarea><input type='hidden' name='code' value='"+comCode+"' /><br/><input type='submit' class='form-submit' id='form-reply' name='new_reply' value='Reply' /></form></center>")
CKEDITOR.replace(res);
/*
var x = document.getElementById("tes");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
*/
i++;
});
})
The following is my css code applied to the anchor tag:
.al {
font-size:11.2px;
text-transform: uppercase;
text-decoration: none;
color:#222;
cursor:pointer;
transition:ease 0.3s all;
}
.al:hover {
color:#0072bc;
}
.link-reply {
color:#767676;
}
Here the arrow icon is displayed but is not clickable
Your code fails, because your <a> elements are created dynamically, whereas the event listener is added only to the elements available when the document has loaded.
In order to get your code to work, you need to use event delegation; that is to add the event listener to a common static ancestor, such as the document or the body, that will in turn delegate it to your target elements.
The methods you can use to achieve this effect in jQuery are on and one, with the latter fitting your case better, if you are trying to attach one-time event listeners.
Code:
$(document).one("click", "a#reply", function() {
// ...
});
Use on for dynamic created events on DOM.
$(document).on("click","a#reply" , function() {
console.log('a#reply => clicked!')
});
Or
$(body).on("click","a#reply" , function() {
console.log('a#reply => clicked!')
});

Highlight the text in textarea with delay

I am trying to highlight the single line of text in <textarea> with time delay. And I am wondering if I can choose a different color? The thing I wanted is when I click on the first <button>, the first line is highlighted into blue, click on the second <button>, 1 second later, the second line is highlighted into blue, lastly click on the third <button>, 2 second later, the third line is highlighted into yellow. I noticed I have a bug that I clicked on the button 3 times then the highlight doesn't work, but it is okay for me, I just want to know how to make the time delay and highlight with a different color. Thank you very much.
$( document ).ready(function() {
var str = 'line 1\nline 2\nline 3\n';
var textNumChar = str.length;
$('#str').val(str);
startPosition = 0;
$(".lines").click(function() {
var tarea = document.getElementById('str');
for(i=startPosition;i<textNumChar;i++)
{
if(str[i]=='\n') {
endposition = i;
break;
}
}
tarea.selectionStart = startPosition;
tarea.selectionEnd = endposition;
startPosition = endposition+1;
});
});
#container {
float: left;
}
button {
width: 50px;height: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<div id="container">
<button class="lines" id="line1">line 1</button>
<br>
<button class="lines" id="line2">line 2</button>
<br>
<button class="lines" id="line3">line 3</button>
</div>
<textarea id="str" rows="6"></textarea>
You can use setTimeout() to set the delay in highlighting the text based on button id.
And ::selection css selector to style the portion of an element that is selected.
$( document ).ready(function() {
var str = 'line 1\nline 2\nline 3\n';
var textNumChar = str.length;
$('#str').val(str);
startPosition = 0;
$(".lines").click(function(e) {
var tarea = document.getElementById('str');
for(i=startPosition;i<textNumChar;i++)
{
if(str[i]=='\n') {
endposition = i;
break;
}
}
var time = 0;
var tar_id = e.target.id;
var colors;
if(tar_id == 'line1' ) { colors = 'red'; }
else if(tar_id == 'line2' ) { time = 1000; colors = 'blue'; }
else if(tar_id == 'line3' ) { time = 2000; colors = 'green'; }
setTimeout(function(){
tarea.selectionStart = startPosition;
tarea.selectionEnd = endposition;
startPosition = endposition+1;
$('body').addClass(colors);
}, time);
});
});
#container {
float: left;
}
button {
width: 50px;height: 30px;
}
.red ::selection {
color: red;
background: yellow;
}
.blue ::selection {
color: blue;
background: red;
}
.green ::selection {
color: green;
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<div id="container">
<button class="lines" id="line1">line 1</button>
<br>
<button class="lines" id="line2">line 2</button>
<br>
<button class="lines" id="line3">line 3</button>
</div>
<textarea id="str" rows="6"></textarea>

Categories