JavaScript dom.style.display not working at all - javascript

So I have a button in my HTML and when I click that button, I want to remove some elements from the page.
currently I have a function something like this which sets the listener for that button.
function addListener_close(elem,i){
console.log("IN BUTTON");
elem.addEventListener("click", function(){
console.log("clicked");
//this returns 'block' which is the current display
console.log(document.getElementById("newsentry-author").style.display);
//set the display to none
document.getElementById("newsentry-author").style.display = "none";
//this returns 'none' which is the new value
console.log(document.getElementById("newsentry-author").style.display);
});}
However, in my HTML page, none of the elements' style changed after I click the button.
Where did I do wrong?
UPDATE HTML CODE
<div class="newsentry-clicked">
<img class= "newsimage" src="https://dynaimage.cdn.cnn.com/cnn/digital-images/org/044409cb-e6f2-4c5b-8eaf-26078a4edef2.jpg">
<div class="newsentry-text">
<div class="newsentry-title">Commuting in the time of coronavirus in the nation's largest subway system</div>
<div class="newsentry-author"><span style="font-weight: bold">Author: </span>Lebron James</div>
<div class="newsentry-source"><span style="font-weight: bold">Source: </span>google.com</div>
<div class="newsentry-date"><span style="font-weight: bold">Date: </span>2020/03/02</div>
<div class="newsentry-desc-clicked">Crowded trains each weekday carry more than 5 million people hardened by terror threats and track-dwelling rats, daylight assaults and diluvial water main breaks. COVID-19 is their latest worry. The spread of the virus has unleashed anxiety across the nation'…</div>
See Original Post
</div>
<div class="close-button">×</div>
The function is bound to .close-button using javascript addEventListener

Related

Get first div after button is clicked

I have the following bit about shop info:
<h3 class="-center"><shop>Shop name</shop></h3>
<button type="button" id="banff" onclick="showShop(this.id)"><shop-title><b>Bakery Shop</b></shop-title></button>
<p class="move-right"><shop-info>Shop Address · Shop number</shop-info></p>
<div id="shop" class="hidden">
<p><shop-info>Opening soon</shop-info></p>
</div>
What I'm trying to do is that once the button is clicked, it will get the first div after the button and toggle the hidden class without referencing the id, there will be multiple shops so I am trying to create one function which will work for all of them rather than create an individual function for each.
I thought I could do something like:
function showShop(id) {
const elem = document.getElementById(id);
alert(id);
const div = elem.closest('div');
div.classList.toggle('hidden');
}
But it's referencing the first div on the page rather than the first one after the button, where have I gone wrong here? Or do I need to go about this a different way?
Thanks in advance for any advice
What about connecting the button id with the div id?
something like:
<h3 class="-center"><shop>Shop name</shop></h3>
<button type="button" id="button-1" onclick="showShop(this.id)">
<shop-title><b>Bakery Shop</b></shop-title>
</button>
<p class="move-right"><shop-info>Shop Address · Shop number</shop-info></p>
<div id="shop-button-1" class="hidden">
<p><shop-info>Opening soon</shop-info></p>
</div>
and in the javascript code would be possible to simplify to:
function showShop(id) {
const elem = document.getElementById(id);
const div = document.getElementById('shop-' + id);
div.classList.toggle('hidden');
}
You should try and avoid using ids as they are difficult to keep track of. Instead you should navigate relative to the clicked button. Below is a script that can easily take care of multiple shop sections without using any ids:
document.querySelectorAll("button").forEach(btn=>{
for(var div=btn;div=div.nextElementSibling;)
if(div.tagName==="DIV") break;
if(div) btn.onclick=()=>div.classList.toggle("hidden")
})
.hidden {display:none}
<h3 class="-center"><shop>Shop name</shop></h3>
<button><shop-title><b>Bakery Shop</b></shop-title></button>
<p class="move-right"><shop-info>Shop Address · Shop number</shop-info></p>
<div class="hidden">Info on bakery shop:
<p><shop-info>Opening soon</shop-info></p>
</div>
<button><shop-title><b>Iron Monger</b></shop-title></button>
<p class="move-right"><shop-info>Shop Address · Shop number</shop-info></p>
<div class="hidden">Info on iron monger's:
<p><shop-info>already open!</shop-info></p>
</div>
<button><shop-title><b>Fish Monger</b></shop-title></button>
<p class="move-right"><shop-info>Shop Address · Shop number</shop-info></p>
<div class="hidden">Info on fish monger's:
<p><shop-info>will never open!</shop-info></p>
</div>
In my latest update I tweaked the snippet again so that now I do the "relative navigation to the associated <div>" only once: at the time when I define and add the onclick eventlistener.

How to run a function after one is done (or after an item in an array loads)?

I'm trying to animate a chat. I have a function that loads the blue messages one at a time each time you press the input field/button. Now, I want the grey messages to appear one at a time automatically after the LAST blue message appears. The JS code I have now has them appearing automatically after the first blue message instead (with a one second delay).
HTML
<div class="messages">
<div class="blue invisible" id="msg1">Hi! I'm looking for an old friend. She attended Martin Grove a few years ago.</div>
<div class="blue invisible" id="msg2">Her name is Sam. *insert pic of Sam and MC*</div>
<div class="blue invisible" id="msg3">Did you know her or her last name by any chance? </div>
<div class="grey" id="msg4" style="display: none;">Hello there!</div>
<div class="grey" id="msg5" style="display: none;">Unfortunately, I did not have the pleasure of teaching Sam. Her last name and whereabouts are a mystery to me as well. </div>
</div>
<div class="input" id="chat-button" onClick="showMessage()">
</div>
CSS
.invisible {
display: none;
}
JS
const myHTMLCollection = document.getElementsByClassName("invisible");
const HTMLElementsArr = [...myHTMLCollection];
function blueMessage() {
if (HTMLElementsArr.length > 0) {
HTMLElementsArr.shift().classList.remove('invisible');
greyMessage();
}
}
function greyMessage() {
setTimeout("show_second()", 1000);
}
function show_second() {
document.getElementById("msg4").style.display = "block";
setTimeout("show_third()", 1000);
}
function show_third() {
document.getElementById("msg5").style.display = "block";
}
Call greyMessage() only when the array is empty, so replace:
greyMessage()
with:
if (!HTMLElementsArr.length) greyMessage();
As a side note, it is bad practice to pass a string as callback argument to setTimeout. Pass the function object (without parentheses). So, for example, replace:
setTimeout("show_second()", 1000);
with:
setTimeout(show_second, 1000);

Add function to game on "True or False" on pure js

I am making a on js "True or False" game. Assertion titles appear on the screen one by one. The user responds to each statement in turn. There are 5 statements in total. - If the user clicked on the False button then the following statement appears. And if it's true then a description appears. You can go to the next question by clicking on the white circle under the headings, which turns into red if an answer has already been given to it (any) or by clicking on further.
What is the best way to make the questions change without reloading the page and make the navigation circles are active in pure js? The available code and an approximate view of the functionality are below:
<h1>statement 1</h1>
<div id="text" style="display:none;">Text of statement</div>
<button onclick="chpok('text')"><h2 onclick="chpok('arrow')">True</h2></button>
<button onclick="chpok('arrow')"><h2>False</h2></button>
<h2 id="arrow" onclick="chpok('block1')" style="display:none;">Next</h2>
<div class="block1" id="block1" style="display: none;">
<h1>statement 2</h1>
<div id="text2" style="display:none;">Text of statement</div>
<button onclick="chpok('text2')"><h2 onclick="chpok('arrow2')">True</h2></button>
<button onclick="chpok('arrow2')"><h2>False</h2></button>
<h2 id="arrow2" onclick="chpok('block2')" style="display:none;">Next</h2>
</div>
<div class="block2" id="block2" style="display: none;">
<h1>statement 3</h1>
<div id="text3" style="display:none;">Text of statement</div>
<button onclick="chpok('text3')"><h2 onclick="chpok('arrow3')">True</h2></button>
<button onclick="chpok('arrow3')"><h2>False</h2></button>
<h2 id="arrow3" style="display:none;">Next</h2>
</div>
<script>function chpok(id) {
elem=document.getElementById(id);
state=elem.style.display;
if (state=='none') elem.style.display='';
}</script>
This is a very broad question, but I'm gonna try and answer it by breaking it down a bit.
There's actually three issues in this question.
How do i display information from JS in the DOM?
How can i act on a button press to update this information?
How can we track which questions was answered?
Let's start with issue #1: For a task like this it helps making the question structure in JavaScript or JSON first. Every question has 4 pieces of information: statement, description, correctAnswer, answer.
We also need to create a function that handles assigning the values into the DOM. In this example we will call it selectTask(id) we're gonna run this on launch.
For Issue #2 we can reuse the selectTask(id) function to display the next answer, but we should add another function called answer(value) which takes what you've answered as an argument, this function sets the answer field of your statement object and calls selectTask for the next task. To run JS function you can use "onclick".
Finally, for issue #3, we have to apply some styling to the overview buttons to indicate which are correct or false, and whether they're answered at all. Luckily we have our answer field for each task already so we can use this. I also added selectTask in the onclick of each of the overview buttons to enable navigation back and forth.
var currentTask = 0;
var tasks = [
{
statement:"Food and water is essential to surviving",
description: "Consuming edibles and liquids is a crucial part of human survival.",
correctAnswer: true,
answer:null
},
{
statement:"Asking questions on SA is stupid",
description: "Despite what some may think, asking question on stack overflow doesn't make you a bad programmer",
correctAnswer: false,
answer:null
},
{
statement:"Computer science is fun!",
description: "Enough said.",
correctAnswer: true,
answer:null
}
]
function selectTask(id){
if(id < 0 || id >= tasks.length) return; //Invalid ID entered.
currentTask = id;
document.getElementById("statement").innerText = tasks[currentTask].statement
document.getElementById("description").innerText = tasks[currentTask].description
}
function answer(value){
tasks[currentTask].answer = value;
console.log(value, currentTask)
for(var task in tasks){
if(tasks[task].answer === null){ /* do nothing*/}
else if(tasks[task].answer === tasks[task].correctAnswer)
document.getElementById("task"+task).style.backgroundColor = "green"
else if(tasks[task].answer !== tasks[task].correctAnswer)
document.getElementById("task"+task).style.backgroundColor = "red"
}
if(currentTask < tasks.length-1){
selectTask(currentTask+1)
}
}
selectTask(0);
<div>
<p id="statement"></p>
<p id="description"></p>
<button onclick="javascript:answer(true)">True</button>
<button onclick="javascript:answer(false)">False</button>
<div id="overview">
<button id="task0" onclick="javascript:selectTask(0)">1</button>
<button id="task1" onclick="javascript:selectTask(1)">2</button>
<button id="task2" onclick="javascript:selectTask(2)">3</button>
</div>
</div>

How to pass text from one page to another by clicking on div using JQuery/JavaScript

I'm making a school project and i am stuck here for almost a week. what i am trying to get is... I have 2 pages
PAGE 1 have more than five divs with different titles. I want to copy that specific title that the user clicks on and want to paste it on PAGE 2. I have tried so many ways but still not getting the answer.
<!--Page 1 Start-->
<section class="main-content">
<div class="blog-cards egypt">
<div class="blog-card-details">
<h2 class="card-title">Div 1</h2>
Abū Sulţān <span>•</span> Egypt
</div>
</div>
<div class="blog-cards london">
<div class="blog-card-details">
<h2 class="card-title">Div 2</h2>
Kensington and Chelsea <span>•</span> London
</div>
</div>
</section>
<!--Page 1 End-->
<!--Page 2 Start-->
<section class="page2-main">
<h3 class="result-show-here"></h3>
</section>
What i want is if i click Div 1 it will show text of .card-title on Page 2 .result-show-here. and if i click Div 2 it will show text of .card-title on Page 2 .result-show-here. and i don't want to change the class
https://www.w3schools.com/html/html5_webstorage.asp
Use localStorage or sessionStorage:
$('div').on('click', function() {
localStorage.text = $(this).find('a').val(); //or sessionStorage.text
});
and
$('.result-show-here').html(localStorage.text);//or sessionStorage.text
First create a page handler on your script using jQuery:
var pg
switch (pg) {
case 'page1':
//the code for page1
break;
case 'page2':
//the code for page2
break;
}
In your case:
for page1:
on your HTML-Page:
<script>pg = 'page1';<script>
and in your script:
//the code for page1
$('div').on('click', function() {
localStorage.text = $(this).find('a').val();
});
for page2:
on your HTML-Page:
<script>pg = 'page2';<script>
and in your script:
//the code for page2
$('.result-show-here').html(localStorage.text);
Based on your case.
I prefer to add a class on the a-tag like <a class="city">London</a>
and get the right value:
//the code for page1
$('div').on('click', function() {
localStorage.text = $(this).find('.city').val();
});
If your pages are hosted by some sort of webserver you can use websockets to communicate/share data.
If your pages are opened on the same machine/browser without any server i would recommend using the browsers session- or localstorage objects.
To set a value use:
sessionStorage.myValue = 'value'
To get a value use:
var val = sessionStorage.myValue
Take a look here.

What would fix a link within a div that is currently used as a clickable div

Hello I have a site I am working on an for this site I am making three panels flip when they are clicked on, you can think of it as a flip card concept. I have everything working but I realized that since the div itself is wrapped in an anchor tag and has a display of "block". What I have is the content inside that are links to external pages but since the div is clickable it only reads that anchor. I tried using the z-index but that doesn't seem to help as all.
This is my markup:
What is ElectedFace?
<div class="flip_content" id="flip1">
<div class="content-info">
<h5 style="text-align:center; font-size:20px; margin:3px 0 0 0; font-family:Arial, Helvetica, sans-serif;"><span class="blue">Elected</span><span class="red">face</span></h5>
<p>electedface is America's free social network delivering more real time news, faster than any other website.</p>
<p>electedface connects subscribers to their elected officials with active electedface accounts</p>
<p>electedface empowers subscribers to share their voice and turn social networking into constructive civil action.</p>
</div>
</div>
<a href="#" class="flip_switch" data-content_container="#flip2" data-flip_container="#flip_box2">
<div class="flipbox" id="flip_box2">
<h4>Getting Started</h4>
</div>
</a>
<div class="flip_content" id="flip2">
<div class="content-info">
<p> There are three ways to connect:</p>
<p>Read top news stories and Read local news stories</p>
<p>Connect to your elected officials and start a group in your community</p>
<p>Register for free membership</p>
</div>
</div>
<a href="#" class="flip_switch" data-content_container="#flip3" data-flip_container="#flip_box3">
<div class="flipbox" id="flip_box3">
<h4>Next Steps</h4>
</div>
</a>
<div class="flip_content" id="flip3">
<div class="content-info">
<p>Elected officials: activate your electedface account, connect to your electorate, and enlist supporters.</p>
</div>
</div>
Heres my Javascript
<script type="text/javascript">
$(function(){
$('.flip_switch').bind("click",function(){
var element = $(this);
var content = element.data("content_container");
var flip_container = element.data("flip_container");
var active_flipbox = $('.activeFlip');
if(element.hasClass('activeFlip')){
//If the flipbox is already flipped
flip_container.revertFlip();
}
else{
if(active_flipbox){
//Revert active flipbox
active_flipbox.revertFlip();
//Remove active status
active_flipbox.removeClass('activeFlip');
}
$(flip_container).flip({
direction: 'rl',
color: '#c8cbce',
content: $(content).html(),
speed:100,
onBefore: function(){
$(flip_container).addClass('activeFlip');
}
});
}
return false;
});
});
</script>
It seems to me your problem is so called bubbling
What you need is (most likely :) :
http://api.jquery.com/event.stopPropagation/

Categories