How to change the id of an element in html using javascript? - javascript

It is my first time using JavaScript. I am trying to make a button where every time visitors click, it'll show another extra line of text. I often get an error on my JavaScript, and I'm not sure how to fix it. Thank you so much!
HTML;
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="container">
<div class="text">
<div class="one hide">
One
</div>
<div class="two hide">
Two
</div>
<div class="three hide">
Three
</div>
</div>
</div>
</body>
<script src="script.js"></script>
</html>
JS;
const text = document.querySelector('.text');
const hide = document.querySelector('.hide');
const one = document.querySelector('.one');
const two = document.querySelector('.two');
var hr1 = document.getElementById('hr1');
var hr2 = document.getELementById('hr2');
var hr3 = document.getElementById('hr3');
hr1.addEventListener('click', () => {
one.classList.remove('hide');
hr1.id = "hr2";
})
// I often get an error on hr2.addEventListener
hr2.addEventListener('click', () => {
two.classList.remove('hide');
hr2.id = "hr3";
})

Your code throws error because you are trying to set hr2 and hr3 when they are not exist.
You need to set hr2 and hr3 variables after setting id's of them like below:
hr1.id = "hr2";
hr2= document.getElementById('hr2');
const text = document.querySelector('.text');
const hide = document.querySelector('.hide');
const one = document.querySelector('.one');
const two = document.querySelector('.two');
var hr1 = document.getElementById('hr1');
var hr2 = null;
var hr3 = null;
hr1.addEventListener('click', () => {
//one.classList.remove('hide');
hr1.id = "hr2";
hr2= document.getElementById('hr2');
console.log(hr2);
hr2.addEventListener('click', () => {
two.classList.remove('hide');
hr2.id = "hr3";
hr3 = document.getElementById('hr3');
console.log(hr3);
})
})
// I often get an error on hr2.addEventListener
<div class="container">
<div class="text">
<div class="one hide">
One
</div>
<div class="two hide">
Two
</div>
<div class="three hide">
Three
</div>
</div>
clickme
</div>

Related

Why event listener does'n work others time same as first?

I have problem with this javascript code that I cant solve at all
btnClaim.addEventListener("click", () => {
rewardCurrent.style.display = "none";
claimedRewards.push(currentReward);
rewardsList.innerHTML = ``;
claimedRewards.forEach(function (rew, i) {
const html = `
<div class="reward">
<div class="img-text-cont">
<img src="${rew.imgUrl}" alt="">
<div class="text-cont">
<p class="claimed-reward-title">${rew.title}</p>
<p class="claimed-reward-price">$${rew.price}</p>
</div>
</div>
<div class="claimed-rewards-action">
<button class="btn-sell2" id="${i}">Sell</button>
<button class="btn-ship">Ship</button>
</div>
</div>
`;
rewardsList.insertAdjacentHTML("afterbegin", html);
});
const btnsShip = document.querySelectorAll(".btn-ship");
const btnsSell = document.querySelectorAll(".btn-sell2");
btnsSell.forEach(function (sell) {
sell.addEventListener("click", () => {
balance += Number(claimedRewards[sell.id].price);
balanceSum.textContent = `$${balance}`;
claimedRewards.splice(Number(sell.id), 1);
rewardsList.innerHTML = ``;
claimedRewards.forEach(function (rew, i) {
const html = `
<div class="reward">
<div class="img-text-cont">
<img src="${rew.imgUrl}" alt="">
<div class="text-cont">
<p class="claimed-reward-title">${rew.title}</p>
<p class="claimed-reward-price">$${rew.price}</p>
</div>
</div>
<div class="claimed-rewards-action">
<button class="btn-sell2" id="${i}">Sell</button>
<button class="btn-ship">Ship</button>
</div>
</div>
`;
rewardsList.insertAdjacentHTML("afterbegin", html);
});
});
});
btnsShip.forEach(function (ship) {
ship.addEventListener("click", () => {
claimedRewardsClose.style.display = "none";
wheelCont.style.filter = "blur(10px)";
thanksCont.style.display = "flex";
});
});
});
I have claim.addEventListener() that push some products to claimedRewards array, than insertAdjacentHTML() method fill shopping chart with that products information and two buttons(sell and ship), I have problem with sell button, when I click sell button on one product found will transfer back to wallet and this product will disappear from the chart and It is all good, but when I want to sell second product sell button doesn't work, it work if I hit claim button again and add new product, but again I only can sell one product, but second not, again it is possible if I hit again claim button and add new product. Is there any solution for my problem?

Pagination will show first page, but not second or third

I'm trying to set up pagination for some blog posts. It works with the first page, and I check my tests to see if the loop is actually populating the "postsToDisplay" array (which it does), but when I click the second-page button, nothing shows up. I can click the first-page button and it brings the first page of posts back up. For some reason, it won't push the new arrays to the page though.
I've tried adding and taking away tests to see what is working. The array is definitely being populated, and the loop is going through the correct "i" values just fine.
Here's some edited code to reproduce my problem:
//Use this as "scripts.js"
$(document).ready(function() {
var realBlog = document.getElementsByClassName("realBlog");
var postsPerPage = 2;
var $pagination = $(".pagination")
function showPage(page) {
$(realBlog).hide();
let postsToDisplay = [];
for (let i = 0; i < realBlog.length; i += 1) {
if (i >= page * postsPerPage && i <= page * postsPerPage + postsPerPage - 1) {
postsToDisplay.push(realBlog[i]);
console.log(i); //Test to see if the loop is running the correct numbers
$(postsToDisplay[i]).show();
}
}
console.log(postsToDisplay); //Test to see if the array is full
return postsToDisplay;
}
showPage(0);
function createPageNumbers() {
let createUl = document.createElement("ul");
createUl.className = "pageNumbers";
for (let i = 1; i <= Math.ceil(realBlog.length/2); i += 1) {
let createLi = document.createElement("li");
let createA = document.createElement("a");
createA.href = "#" + i;
createA.textContent = i;
createLi.className = "pageButton";
createLi.append(createA);
createUl.append(createLi);
$(".pagination").append(createUl);
createA.addEventListener("click", () => {
showPage(i-1);
});
}
}
createPageNumbers();
});
//Use this as index.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="scripts.js"></script>
</head>
<body>
<div class="container realBlog">
<h1 class="realBlogTitle threeDText">Title</h1>
<p class="entry"></p>
<div class="entryInfo">
<span class="tag1"></span>
<span class="tag2"></span>
<span class="date"></span>
<span class="time"></span>
</div>
<div class="borderBottom"></div>
</div>
<div class="container realBlog">
<h1 class="realBlogTitle threeDText">Title</h1>
<p class="entry"></p>
<div class="entryInfo">
<span class="tag1"></span>
<span class="tag2"></span>
<span class="date"></span>
<span class="time"></span>
</div>
<div class="borderBottom"></div>
</div>
<div class="container realBlog">
<h1 class="realBlogTitle threeDText">Title</h1>
<p class="entry"></p>
<div class="entryInfo">
<span class="tag1"></span>
<span class="tag2"></span>
<span class="date"></span>
<span class="time"></span>
</div>
<div class="borderBottom"></div>
</div>
<div class="pagination"></div>
</body>
</html>
Page 1 should show posts 1 and 2, page 2 should show post 3.
Alright, I found the answer, and of course, it's a silly mistake. I have this little snippet: $(postsToDisplay[i]).show();
I'm not sure why I'm trying to show each 'i' when I can just show the whole array... So the fix is $(postsToDisplay).show();

Javascript Function back to it's original place

I'm not actually a programmer but I have to do this website work properly. And for that I'll need your help.
I'm messing with some javascript and I manage to maek this:
<script>
function funcaosabores1() {
document.getElementById("testeagora1").innerHTML = "";
document.getElementById('contento1').style.visibility="visible";
document.getElementById('contento2').style.visibility="hidden";
document.getElementById('contento3').style.visibility="hidden";
document.getElementById('contento4').style.visibility="hidden";
document.getElementById('contento5').style.visibility="hidden";
}
function funcaosabores2() {
document.getElementById("testeagora2").innerHTML = "";
document.getElementById('contento2').style.visibility="visible";
document.getElementById('contento1').style.visibility="hidden";
document.getElementById('contento3').style.visibility="hidden";
document.getElementById('contento4').style.visibility="hidden";
document.getElementById('contento5').style.visibility="hidden";
}
function funcaosabores3() {
document.getElementById("testeagora3").innerHTML = "";
document.getElementById('contento3').style.visibility="visible";
document.getElementById('contento1').style.visibility="hidden";
document.getElementById('contento2').style.visibility="hidden";
document.getElementById('contento4').style.visibility="hidden";
document.getElementById('contento5').style.visibility="hidden";
}
function funcaosabores4() {
document.getElementById("testeagora4").innerHTML = "";
document.getElementById('contento4').style.visibility="visible";
document.getElementById('contento1').style.visibility="hidden";
document.getElementById('contento2').style.visibility="hidden";
document.getElementById('contento3').style.visibility="hidden";
document.getElementById('contento5').style.visibility="hidden";
}
function funcaosabores5() {
document.getElementById("testeagora5").innerHTML = "";
document.getElementById('contento5').style.visibility="visible";
document.getElementById('contento1').style.visibility="hidden";
document.getElementById('contento2').style.visibility="hidden";
document.getElementById('contento3').style.visibility="hidden";
document.getElementById('contento4').style.visibility="hidden";
}
</script>
And I can't find on how to make for example: funcaosabores1 is clicked and is now visible, when I click funcaosabores2, the first one is hidden and the second is showing. But I can't click on the first one back because it was already clicked. (Idk if it's called return)
This is the div's called in the script:
<div class="animacao_saborgingerale" id="contento2" style="visibility:hidden;"></div>
<div class="animacao_saboruvasyrah" id="contento3" style="visibility:hidden;"></div>
<div class="animacao_sabortangerina" id="contento4" style="visibility:hidden;"></div>
<div class="animacao_saboruvabranca" id="contento5" style="visibility:hidden;"></div>
<div class="sabor-melancia"><p onclick="funcaosabores1()" id="testeagora1">MELANCIA</p> </div>
<div class="sabor-gingerale"><p onclick="funcaosabores2()" id="testeagora2">GINGER ALE</p></div>
<div class="sabor-uvasyrah"><p onclick="funcaosabores3()" id="testeagora3">UVA SYRAH</p></div>
<div class="sabor-tangerina"><p onclick="funcaosabores4()" id="testeagora4">TANGERINA</p></div>
<div class="sabor-uvabranca"><p onclick="funcaosabores5()" id="testeagora5">UVA BRANCA</p></div>
This seems quite messy but I'm here if you guys can help me! Thanks.
The CodePen of how it is right now. #nielsdebruin
I think you just want to do something like this:
let prevButton;
let prevContent;
function toggle(e) {
if (prevButton) prevButton.style.visibility = 'visible';
prevButton = e.target;
e.target.style.visibility = 'hidden';
let id = e.target.id;
let number = id.slice(-1);
if (prevContent) prevContent.style.visibility = 'hidden';
prevContent = document.getElementById('contento' + number);
prevContent.style.visibility = 'visible';
}
<div class="content animacao_saborgingerale" id="contento1" style="visibility:hidden;">1</div>
<div class="content animacao_saborgingerale" id="contento2" style="visibility:hidden;">2</div>
<div class="content animacao_saboruvasyrah" id="contento3" style="visibility:hidden;">3</div>
<div class="content animacao_sabortangerina" id="contento4" style="visibility:hidden;">4</div>
<div class="content animacao_saboruvabranca" id="contento5" style="visibility:hidden;">5</div>
<div class="button sabor-melancia"><p onclick="toggle(event)" id="testeagora1">MELANCIA</p> </div>
<div class="button sabor-gingerale"><p onclick="toggle(event)" id="testeagora2">GINGER ALE</p></div>
<div class="button sabor-uvasyrah"><p onclick="toggle(event)" id="testeagora3">UVA SYRAH</p></div>
<div class="button sabor-tangerina"><p onclick="toggle(event)" id="testeagora4">TANGERINA</p></div>
<div class="button sabor-uvabranca"><p onclick="toggle(event)" id="testeagora5">UVA BRANCA</p></div>

How to loop through JavaScript object in HTML?

I want to loop through a JavaScript object and repeat an html script as many times as the object length.
Here, I have the following in a script tag
<script>
var obj;
ipcRenderer.on('requests-results', (event, hosSchema) => {
obj = hosSchema
})
</script>
obj is an array retrieved from Mongo database as the picture below shows:
and I have the following inside <body> tag:
<div class="row">
<div class="col-md-4 col-sm-4">
<div class="card">
<div class="card-content">
<span class="card-title">.1.</span>
<p>.2.</p>
</div>
<div class="card-action">
.3.
.4.
</div>
</div>
</div>
</div>
How can I loop through obj to repeat the code between <div> tag as many times as obj.length?
I would suggest you to use Handlebars as #Amit mentioned.
first move out the code inside <div id="page-inner"> as below:
<div id="page-inner">
</div>
<script id= "requests-template" type="text/x-handlebars-template">
<div class="row">
{{#each requests}}
<div class="col-md-4 col-sm-4">
<div class="card">
<div class="card-content">
<span class="card-title">{{this.fieldName}}</span>
<p>{{this.fieldName}}</p>
</div>
<div class="card-action">
{{this.fieldName}}
{{this.fieldName}}
</div>
</div>
</div>
{{/each}}
</div>
</script>
Then inside another script page of type text/javascript you create the requests and assigned obj/hosSchema to it as below:
<script type="text/javascript">
var requestInfo = document.getElementById('requests-template').innerHTML;
var template = Handlebars.compile(requestInfo);
var requestData = template({
requests: obj
})
$('#page-inner').html(requestData);
</script>
NOTE: you need handlebars package installed (npm install handlebars --save)
Use templating script like Handlebars.js, Mustache.js or underscore.js.
Check below link for more description.
http://www.creativebloq.com/web-design/templating-engines-9134396
Try this:
var divlist = document.getElementsByTagName['div'];
var duplicate = null;
var rowIndex = -1;
var found = false;
for(var i = 0;i<obj.length;i++)
{
if(!found)
for(var p = 0;p<divlist.length;p++)
{
if(rowIndex != -1 && duplicate != null)
{
//set a Boolean to true and break
found = true;
break;
}
if(divlist[p].className == "col-md-4 col-sm-4")
{
//copy the element
duplicate = divlist[p];
}
else if(divlist[p].className == "row")
{
//identify the row's index
rowIndex = p;
}
}
//append the duplicate
divlist[rowIndex].appendChild(duplicate);
}

Set CSS property with js click event handler

I am trying to create an onclick event which will show/hide elements of an array however I am struggling with the showSubTabGroup() function below.
Sidenote: Eventually I would like to make this onmouseenter and onmouseleave, rather than 'click' as you see below.
I would like to be able to click on a div and show subsequent div's below as you might expect from a navigation feature.
The console is not returning any errors, however the 'click' function seems alert("CLICKED") properly.
Any help would be greatly appreciated.
Problem:
Tab.prototype.showSubTabGroup = function (tabIndex, subTabIndex) {
this.tab[tabIndex].addEventListener('click', function () {
alert("CLICKED");//Testing 'click' call
for (var i = subTabIndex; i < this.subTabGroup; i++) {
this.subTab[i].style.display = "";
}
});
}
function Tab (subTabGroup) {
this.tab = document.getElementsByClassName("tab");
this.subTab = document.getElementsByClassName("sub-tab");
this.subTabGroup = subTabGroup;
}
Tab.prototype.hideSubTabs = function () {
for (var i = 0; i < this.subTab.length; i++) {
this.subTab[i].style.display = "none";
}
}
Tab.prototype.showSubTabGroup = function (tabIndex, subTabIndex) {
this.tab[tabIndex].addEventListener('click', function () {
for (var i = subTabIndex; i < this.subTabGroup; i++) {
this.subTab[i].style.display = "";
}
});
}
var tab = new Tab(3);
tab.hideSubTabs();
tab.showSubTabGroup(0,0);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Responsive Nav</title>
</head>
<body>
<!-- JQuery CDN -->
<script src="http://code.jquery.com/jquery-3.1.0.js"></script>
<div class="container">
<div class="tab">
<p>TAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
</div>
<div class="container">
<div class="tab">
<p>TAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
</div>
<div class="container">
<div class="tab">
<p>TAB</p>
</div>
<div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
</div>
</div>
<script type="text/javascript" src="tab.js"></script>
<script type="text/javascript" src="tabEvents.js"></script>
</body>
</html>
The problem of what is this inside the click. It is not your tab code, it is the reference to the element that you clicked on. You need to change that by using bind
Tab.prototype.showSubTabGroup = function (tabIndex, subTabIndex) {
this.tab[tabIndex].addEventListener('click', (function () {
for (var i = subTabIndex; i < this.subTabGroup; i++) {
this.subTab[i].style.display = "";
}
}).bind(this));
}
As I read your post, I assume hideSubTabs() is working properly. In that case I will suggest to use in showSubTabGroup():
this.subTab[i].style.display = "initial";
instead of
this.subTab[i].style.display = "";
"initial" will set to its default e.g. as "block" for div and "inline" for span
I see that you also have included jQuery. If I may ask why don't jQuery functions which will do the same with less code:
$('.tab').on('click',function() {
$(this).closest('.container').find('.sub-tab').toggle()
})
$('.tab').click();
$('.tab')[0].click();

Categories