I have two buttons SHOW and HIDE. When show is clicked numbers will appear (which are json files, each json file contain only one number 1, 2, 3..) when HIDE is clicked first number(json) in a row dissapear. For example we clicked SHOW button 3 times and got this: 1 2 3 and then clicked HIDE once then we got: 2 3 shown. My problem is when HIDE is clicked I want to save that deleted number by showing it in my div where id="nome". After another clicking on button HIDE another hidden number is shown and old is deleted from div.
var pageCounter = 1;
var pageCounterr = 1;
var animalContainer = document.getElementById("animal-info");
var animalContainerr = document.getElementById("nome");
var btn = document.getElementById("btn");
var btnn = document.getElementById("btnn");
btn.addEventListener("click", function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://10.0.9.243/animals-' + pageCounter + '.json');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
renderHTML(ourData);
};
ourRequest.send();
pageCounter++;
});
function renderHTML(data) {
var htmlString = document.createElement("div");
for (i = 0; i < data.length; i++) {
let pText = document.createTextNode(data[i].name);
let pElement = document.createElement("p");
pElement.append(pText);
htmlString.append(pElement);
htmlString.classList.add('containers') // new Line added
}
animalContainer.append(htmlString);
}
btnn.addEventListener("click", function() {
let containers = document.getElementsByClassName('containers');
if (containers.length > 0) {
containers[0].remove();
}
});
<button id="btn">SHOW</button>
<button id="btnn">HIDE</button>
<h2>Numbers:</h2>
<div id="animal-info"></div>
<h2>Hidden number is:</h2>
<div id="nome"></div>
Related
This code is not creating a single div in the webpage which i linked the js below. how can i makes changes in the js or html for the code to be executed as expected
var div,
container = document.getElementById("container");
for (var i = 0; i < 5; i++) {
div = document.createElement("div");
div.onclick = function () {
alert("This is box #" + i);
};
container.appendChild(div);
}
1) To show a div you have to include some text inside divtag
2) You should use let instead of var to get the correct number when user click on div
var div,
container = document.getElementById("container");
for (let i = 0; i < 5; i++) { // change -> let instead of var
div = document.createElement("div");
div.textContent = `div${i}` // change -> add some text
div.onclick = function() {
alert("This is box #" + i);
};
container.appendChild(div);
}
<div id="container"></div>
Javascript
function openPage(pageName, elmnt) {
// Hide all elements with class="tabcontent" by default */
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Show the specific tab content
document.getElementById(pageName).style.display = "block";
}
document
list = document.querySelectorAll(".myTextInputID")
list[1].addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
event.preventDefault();
var input = document.getElementsByClassName("myTextInputID")[0]
.value;
if (input.includes("https://www.amazon.co.uk/")) {
document.getElementsByClassName("containFORM")[0]
.insertAdjacentElement("beforeend", itemcont);
document.getElementById("prodcont")
.insertAdjacentElement("afterbegin", imgcont);
document.getElementsByClassName("containFORM")[0]
.style.backgroundColor = "white"
} else {
var URLerror = document.createElement("p");
URLerror.classList.add("error");
var urlerror = document.createTextNode("This is not an amazon url, please input an amazon url and press enter again.");
URLerror.appendChild(urlerror);
var cont = document.getElementsByClassName("myForm")[0];
cont.insertAdjacentElement("afterend", URLerror);
setTimeout(function() {
URLerror.remove();
}, 2000);
}
}
});
function newTab() {
var allTabs = document.getElementById("navigation2");
var tabList = document.createElement("li");
var error = document.createElement("p");
var eNode = document.createTextNode("You cant track this many products");
var button1 = document.getElementById("button1");
var tabButton = document.createElement("button");
tabButton.setAttribute("onclick", "openPage('1', this, 'red')")
error.classList.add("error");
tabList.classList.add("tabli");
tabButton.classList.add("tabs");
if (button1.offsetWidth < 190) {
error.appendChild(eNode);
document.getElementById("tabcon")
.insertAdjacentElement("afterend", error);
setTimeout(function() {
error.remove();
}, 2000);
} else {
tabList.appendChild(tabButton);
allTabs.insertAdjacentElement("beforebegin", tabList);
var newt = ("window.location.href=")+("\'")+("#")+("newtab")+("\'");
var newtab = document.createElement("div")
newtab.id="#newtab";
newtab.className="containFORM";
// true means clone all childNodes and all event handlers
document.getElementById("0").insertAdjacentElement("afterend", clone)
clone.id = "1";
}
}
When you press the new tab button it makes a new tab and creates a clone of a stored element, however with the class selector I can only put a number (0,1) but I need it so its some sort of variable(x), x being the number of the current tab. So when you click on one tab set x to that and then all logic will be performed on each tab, I can't think of a way to do this without copying what I've done multiple times and just changing the number myself, which doesn't feel very efficient.
I have found this piece of code in JQuery that might help you.
var activeTab = $(".tab-content").find(".active");
console.log(activeTab.context.URL);
If you try it while inspect this very page, you can check that the result is the URL of this page:
https://stackoverflow.com/questions/65886250/how-to-tell-javascript-what-tab-is-active
Note: I know there may be ways to do this in other languages but I have only learned javascript.
I have an array of objects (food items in this case, each item has a name property). I have this code in a for loop that makes buttons for each item in the array (if the first item in the array has a name of cake then cake's button is called cake, if the item is called fries then the buttons name is fries). I want the user to be able to click the button for each item only once, and when that button is clicked, I want to display a list of each item clicked. The reason why I have var click = item[i].name is because I want each button to have the name of the item. This code makes a button for item in the array but it does not list the items clicked on. Here is my code:
HTML
<html>
<head>
</head>
<body>
<p id="likes">Likes: </p>
</body>
</html>
JAVASCRIPT
var items=[
{
name:"cake",
price:12
},
{
name:"fries",
price:10
},
{
name:"apple",
price:11
}
];
window.onload = function() {
for (var i = 0; i < items.length; i++) {
var btnItems = document.createElement("button");
btnItems.id = "btnItems";
btnItems.innerHTML = "Items";
var clicks = items[i].name;
btnItems.onclick = function () {
el.disabled = true;
clicks += items[i].name + i;
document.getElementById("clicks").innerHTML = "Items Clicked" + clicks;
}
}
Style your view as you wish but this should answer your problem
var items = [{
name: "cake",
price: 12
},
{
name: "fries",
price: 10
},
{
name: "apple",
price: 11
}
];
for (let i = 0; i < items.length; i++) {
const btn = document.createElement("button");
btn.id = "btnItems";
btn.textContent = items[i].name;
btn.onclick = function(el) {
// disable your button immediately upon click
el.target.disabled = true;
// create list element and assign value
const li = document.createElement('li');
li.textContent = items[i].name
// append list element to your <ul> list
document.getElementById('list-section').appendChild(li);
}
// append button to the DOM
document.body.appendChild(btn)
}
<ul id="list-section">
</ul>
HTML code:
I created a div to append the buttons in it.
<html>
<head>
</head>
<body>
<p id="likes">Likes: </p>
<p id="clicks"></p>
<div id="btn-container">
</div>
</body>
</html
>
Js code:
var items=[
{
name:"cake",
price:12
},
{
name:"fries",
price:10
},
{
name:"apple",
price:11
}
];
for (var i = 0; i < items.length; i++) {
var btnItems = document.createElement("button");
btnItems.id = "btnItems"+i;
var clicks = items[i].name;
btnItems.innerHTML = clicks;
document.getElementById("btn-container").appendChild(btnItems);
console.log(btnItems);
btnItems.addEventListener('click',function (el) {
alert('here');
el.disabled = true;
clicks += items[i].name + i;
document.getElementById("clicks").innerHTML = "Items Clicked" + clicks;
});
}
As you have not provided a reproducible example I cannot test this, however, you should be able to use something like this. Please take note of the comments and amend where necessary.
window.onload = function() {
for (var i = 0; i < items.length; i++) {
var btnItem = document.createElement("button");
const name = item[i].name;
// Set the button id
btnItem.id = `btnItem-${name}`;
// Set the button text to the item name
btnItem.innerHTML = name
btnItem.addEventListener('click', function (event) {
event.target.disabled = true;
// Do whatever you want here, e.g. add "name" to a list
}
}
}
Here is my html with the JS within. The function "toggleMessage()" is the function I am using to hide and show messages when clicked. The problems I am running into include:
Messages showing by default, when they should hide by default (until clicked).
When clicked, all messages show at once - I want only the messages clicked on to show.
The new messages that populate the page every 3 seconds are not affected by the click event - I want them to be effected.
function newMessage() {
// Loop goes through emails and creats divs for subject, date, sender, and body
var i = 0;
while (i < window.geemails.length) {
//email container
var div = document.createElement("div");
//date
var dateField = document.createElement("h1");
dateField.className = "date";
dateField.innerHTML = window.geemails[i].date;
div.appendChild(dateField);
//subject
var subjectField = document.createElement("h1");
subjectField.className = "subject";
subjectField.innerHTML = window.geemails[i].subject;
div.appendChild(subjectField);
//sender
var senderField = document.createElement("h1");
senderField.className = "sender";
senderField.innerHTML = window.geemails[i].sender;
div.appendChild(senderField);
//body
var bodyField = document.createElement("p");
bodyField.className = "body";
bodyField.innerHTML = window.geemails[i].body;
div.appendChild(bodyField);
//Separate message content into containers
document.getElementById("main").appendChild(div);
//inbox counter
document.getElementById('counter').innerHTML = "You have " + document.getElementsByClassName("date").length + " messages";
window.geemails.shift();
}
}
newMessage();
//interval for loading new messages
function addNewMessage() {
setInterval(function() {
window.geemails.push(getNewMessage());
newMessage();
}, 3000);
}
addNewMessage();
//hiding and showing body message upon click
var messageBox = document.getElementsByClassName("subject");
for (var i = 0; i < messageBox.length; i++) {
messageBox[i].addEventListener("click", toggleMessage);
}
function toggleMessage() {
var showMessage = document.getElementsByClassName('body');
for (var i = 0; i < showMessage.length; i++) {
if (showMessage[i].style.display === 'none') {
showMessage[i].style.display = "block";
} else {
showMessage[i].style.display = "none";
}
}
}
You need a class for your messages and possiblt for their bodies.
Suppose you have a message div with a message body like this
<div class="message">
<div class="message-header">
</div>
<div class="message-body" style="display:none;">
</div>
</div>
if you want the body to be hidden by default use css display:none
then in your javascript do
$('.message').click(function(){
$(this).children('.message-body').show();
});
I have this code that sends the values a user have typed in... the information and numbers are sent as an array and pushed into another array, I then display the text in a dynamically created list element and number in a span element...
var button = $('#add');
button.click(function()
{
var filmnamn = $('#name');
var filmnamnet = filmnamn.val();
var betyg = $('#star');
var betyget = betyg.val();
betyget = Number(betyget);
if(filmnamnet == 0)
{
$('#name').css('background-color', 'red');
}
if(betyget == 0)
{
$('#star').css('background-color', 'red');
}
if(betyget == 0 || filmnamnet == 0)
{
alert("Vänligen fyll i fälten korrekt");
}
else
{
var array = new Array();
array.unshift(betyget);
array.unshift(filmnamnet);
film_array.unshift(array);
betyg_array.unshift(array);
updateFilmList();
}
});
var film_list = $("#filmlista");
var film_array = new Array();
function updateFilmList()
{
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var filmen = film_array[0][0];
var grade = film_array[0][1];
var element = '<li class="lista">' + filmen + '<span class="betyg">'+ grade +'</span></li>';
film_list.append(element);
changeNumber();
}
And at last I have the function that i want to change the number in the span element to the amount of stars that the number shows... this works fine but only for the first created list and span element, when I try to add more listelements the number wont show up as stars, can someone tell me why this happens and point me in the direction to fix the problem?
function changeNumber(){
var elements= document.getElementsByClassName("betyg");
for (var i=0; i<elements.length; i++) {
var element = elements[i];
var length = parseInt(element.innerHTML);
var x=Array(length+1).join("*");
element.innerHTML=x;
}
}