How do I change the content of figcaption using javascript? [duplicate] - javascript

This question already has answers here:
Double quote in JavaScript string
(4 answers)
Closed 2 years ago.
<button onclick="changefigure()">2011</button>
<figure>
<img id="Image" src="NT_Naplan_Reading_Results_2017.png"/>
<figcaption id="caption"><em>Fig 2</em>Percent of children above national minimum standard in
reading in 2017 for Year 3, 5, 7 and 9 for Non-Indigenous and Indigenous children in the
Northern Territory. Data Source NAPLAN results</figcaption>
</figure>
<script>
function changefigure()
{
var x = document.getElementById("Image");
var y = document.getElementById("caption")
x.src = 'NT_Naplan_Reading_Results_2011.png'
//y = "<em>Fig 1</em>Percent of children above national minimum standard in reading in
2017 for Year 3, 5, 7 and 9 for Non-Indigenous and Indigenous children in the Northern
Territory. Data Source NAPLAN results"
}
</script>
So I can't seem to be able to change the figcaption. I've tried using y.innerHTML and y.innertext but both of them dont seem to work. Any tips?

So i found out what's wrong with my code. Instead of using " use ' for it to for.
E.G.
<script>
function changefigure()
{
var x = document.getElementById("Image");
var y = document.getElementById("caption")
x.src = 'NT_Naplan_Reading_Results_2011.png'
y.innerHTML = '<em>Fig 1</em>Percent of children above national minimum
standard in reading in 2017 for Year 3, 5, 7 and 9 for Non-Indigenous and
Indigenous children in the Northern Territory. Data Source <a href="">NAPLAN
results</a>'
}
</script>

Related

Add a row per day or week automatically for multiple years (w/ using script or function ?)

What I would like to do is to create a script or with a function that will add automatically the day, the month and the year per row for 4 years for example in order to make a calendar of shooting, pre production and post prod per film. It would be so long to do it manually and add each day per month for 4 or more years. If it's done by a script it would be done instantly and would be possible to update later to add more years.
Example of what I'm looking for
If it's too complicated per day, I can add per week. Like week 1 January 21, just like in the picture. But I really prefer if that's possible to add a row per day to be the most accurate as possible.
Days for the rest of the year in a column
function daysforrestofyear() {
let days = [];
let dt = new Date();
const ldtv = new Date(dt.getFullYear() + 1,0,1).valueOf();
do {
days.push([Utilities.formatDate(dt,Session.getScriptTimeZone(),"dd/MMM/yyyy")]);
dt.setDate(dt.getDate() + 1);
}while(dt.valueOf() < ldtv)
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet0");
sh.clearContents();
sh.getRange(1,1,days.length,1).setValues(days);
}
Jun/04/2022
Jun/05/2022
Jun/06/2022
Jun/07/2022
Jun/08/2022
Jun/9/2022
Jun/10/2022
Jun/11/2022
Jun/12/2022
Jun/13/2022
Jun/14/2022
Jun/15/2022
Jun/16/2022
Jun/17/2022
Jun/18/2022
Jun/19/2022
Jun/20/2022
Jun/21/2022
Jun/22/2022
Jun/23/2022
Jun/24/2022
Jun/25/2022
Jun/26/2022
Jun/27/2022
Jun/28/2022
Jun/29/2022
Jun/30/2022
Jul/01/2022
Jul/02/2022
Jul/03/2022
Jul/04/2022
Jul/05/2022
Jul/06/2022
Jul/07/2022
Jul/08/2022
Jul/9/2022
Jul/10/2022
Jul/11/2022
Jul/12/2022
Jul/13/2022
Jul/14/2022
Jul/15/2022
Jul/16/2022
Jul/17/2022
Jul/18/2022
Jul/19/2022
Jul/20/2022
Jul/21/2022
Jul/22/2022
Jul/23/2022
Jul/24/2022
Jul/25/2022
Jul/26/2022
Jul/27/2022
Jul/28/2022
Jul/29/2022
Jul/30/2022
Jul/31/2022
Aug/01/2022
Aug/02/2022
Aug/03/2022
Aug/04/2022
Aug/05/2022
Aug/06/2022
Aug/07/2022
Aug/08/2022
Aug/9/2022
Aug/10/2022
Aug/11/2022
Aug/12/2022
Aug/13/2022
Aug/14/2022
Aug/15/2022
Aug/16/2022
Aug/17/2022
Aug/18/2022
Aug/19/2022
Aug/20/2022
Aug/21/2022
Aug/22/2022
Aug/23/2022
Aug/24/2022
Aug/25/2022
Aug/26/2022
Aug/27/2022
Aug/28/2022
Aug/29/2022
Aug/30/2022
Aug/31/2022
Sep/01/2022
Sep/02/2022
Sep/03/2022
Sep/04/2022
Sep/05/2022
Sep/06/2022
Sep/07/2022
Sep/08/2022
Sep/9/2022
Sep/10/2022
Sep/11/2022
Sep/12/2022
Sep/13/2022
Sep/14/2022
Sep/15/2022
Sep/16/2022
Sep/17/2022
Sep/18/2022
Sep/19/2022
Sep/20/2022
Sep/21/2022
Sep/22/2022
Sep/23/2022
Sep/24/2022
Sep/25/2022
Sep/26/2022
Sep/27/2022
Sep/28/2022
Sep/29/2022
Sep/30/2022
Oct/01/2022
Oct/02/2022
Oct/03/2022
Oct/04/2022
Oct/05/2022
Oct/06/2022
Oct/07/2022
Oct/08/2022
Oct/9/2022
Oct/10/2022
Oct/11/2022
Oct/12/2022
Oct/13/2022
Oct/14/2022
Oct/15/2022
Oct/16/2022
Oct/17/2022
Oct/18/2022
Oct/19/2022
Oct/20/2022
Oct/21/2022
Oct/22/2022
Oct/23/2022
Oct/24/2022
Oct/25/2022
Oct/26/2022
Oct/27/2022
Oct/28/2022
Oct/29/2022
Oct/30/2022
Oct/31/2022
Nov/01/2022
Nov/02/2022
Nov/03/2022
Nov/04/2022
Nov/05/2022
Nov/06/2022
Nov/07/2022
Nov/08/2022
Nov/9/2022
Nov/10/2022
Nov/11/2022
Nov/12/2022
Nov/13/2022
Nov/14/2022
Nov/15/2022
Nov/16/2022
Nov/17/2022
Nov/18/2022
Nov/19/2022
Nov/20/2022
Nov/21/2022
Nov/22/2022
Nov/23/2022
Nov/24/2022
Nov/25/2022
Nov/26/2022
Nov/27/2022
Nov/28/2022
Nov/29/2022
Nov/30/2022
Dec/01/2022
Dec/02/2022
Dec/03/2022
Dec/04/2022
Dec/05/2022
Dec/06/2022
Dec/07/2022
Dec/08/2022
Dec/9/2022
Dec/10/2022
Dec/11/2022
Dec/12/2022
Dec/13/2022
Dec/14/2022
Dec/15/2022
Dec/16/2022
Dec/17/2022
Dec/18/2022
Dec/19/2022
Dec/20/2022
Dec/21/2022
Dec/22/2022
Dec/23/2022
Dec/24/2022
Dec/25/2022
Dec/26/2022
Dec/27/2022
Dec/28/2022
Dec/29/2022
Dec/30/2022
Dec/31/2022

Is there a way to remove and HTML element after six hours?

I have a picture with the word "NEW" over it to designate a new document that has been posted to our website. I would like to have jQuery remove the picture after 6 hours of it being posted. How would I go about doing this?
Here is the element:
<tr class="pointer">
<td>
<img class="germ" src="~/Image" width="40px" />
<i class="created" hidden="hidden">April 3, 2020 13:13:00</i>
Document Title
</td>
<td>PDF</td>
<td>March 2020</td>
</tr>
As you can see, I have a hidden <i> element that designates when the document was posted to the website. I need to remove the <img> tag 6 hours from the time in the <i> tag.
How can I do this using jQuery or JavaScript?
This would be better done server-side. The way you want to do it assumes that the user will have this same page up for 6+ hours, or come back to this page in the same state, which is pretty unlikely.
What I would do is add a property to the post for created and have it set a default time of Date.now(), and then have front end code look for whether that created value was less than 6 hours ago (1000 * 60 * 60 * 6 miliseconds).
If so, show the 'New' graphic. If not, don't.
Another way to do it so that you don't have to update server-side stuff that might be more set in stone is to have the default display for the "New" graphic to be true, then:
let createdTime = new Date(document.queryselector('i.hidden').textContent);
if (Date.now() - createdTime > (1000 * 60 * 60 * 6)){
//code to hide the "New" graphic
}
A little extra two cents for free: I would add an id attribute to that hidden i element to make sure you're selecting only that and not something else that may have the same class
Since you asked how to do this with JavaScript or JQuery, this is how.
I also included a 3-second example to show that it does work.
window.setTimeout(function() {
document.getElementById('sixHours').outerHTML = '';
}, 2160000);
window.setTimeout(function() {
document.getElementById('threeSeconds').outerHTML = '';
}, 3000);
<div id="sixHours">This will be removed after six hours</div>
<div id="threeSeconds">This will be removed after three seconds</div>
Keep in mind, that as soon as the page is refreshed, the timer will start over. If you want to avoid this and still have JavaScript handle it, you could have it removed at a definite time.
Edit
The snippet below will parse the date in expiration and find the milliseconds from that till now. Then like the snippet above, the remove element will get removed when the timer expires. 6 hours are added to the timer to make it expire 6 hours from the given time.
var expiration = Date.parse(document.getElementById('expiration').innerHTML);
var diff = expiration - Date.now();
window.setTimeout(function() {
document.getElementById('remove').outerHTML = '';
}, diff + 2160000);
//2160000ms = 6 hours
<div id="expiration">April 3, 2020 20:00:00</div>
<div id="remove">Will be removed by the date above</div>
Use setTimeout(), but bear in mind that people aren't likely going to sit at a single page for 6 hours meaning this will fail as soon as they navigate away. You'll have to change the time sent over every time they refresh.
const testing = true;
if (testing) {
// BEGIN - Fake date for testing
const tmpNow = new Date();
document.querySelector("i.created").innerHTML = tmpNow.toUTCString();
// END - Fake date for testing
}
const d = document.querySelector("i.created").innerHTML;
const dd = new Date(d);
if (testing) {
dd.setSeconds(dd.getSeconds() + 3);
} else {
dd.setHours(dd.getHours() + 6);
}
const ddd = dd.getTime();
const now = Date.now();
if (ddd < now) {
console.log("Too late");
}
const dt = Math.max(ddd - now, 0);
setTimeout(() => {
const img = document.querySelector("img.germ");
img.parentNode.removeChild(img);
}, dt);
<tr class="pointer">
<td>
<img class="germ" src="~/Image" width="40px" />
<i class="created" hidden="hidden">April 3, 2020 13:13:00</i> 03.21.2020 GOA - Alaska Businesses Now Eligible for SBA Economic Injury Disaster Loans (2)
</td>
<td>PDF</td>
<td>March 2020</td>
</tr>
You don't understand the problem here.
As R Greenstreet said it needs to be done server-side. You need a Create Post Date to be sent to UI.
Let's assume you have a JSON coming from a server where you can add createDate property of a post form bata base.
{createDate: date, name......}
You need to compare that date with Date.now()
Pseodu Code here:
if(createDate + 6 hours >= Date.now()) then hide your Icon.
You will need to use Date to convert the String into a Date Object:
new Date("April 3, 2020 13:13:00");
This will create a Date Object, yet since there is no Timezone Offset, the script might assume UTC. Your result might be:
"2020-04-03T13:13:00.000Z"
So consider specifying a Time Zone. Some browsers will assume the Users local Timezone.
$(function() {
function getDate(cObj, tz) {
if (tz == undefined) {
tz = "GMT-07:00";
}
var str = cObj.text().trim() + " " + tz;
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
var nDt = new Date(str);
console.log(str, nDt);
return nDt;
}
function getHoursPast(thn) {
// https://stackoverflow.com/questions/19225414/how-to-get-the-hours-difference-between-two-date-objects/19225463
var now = new Date();
return Math.floor(Math.abs(now - thn) / 36e5);
}
var hours = getHoursPast(getDate($(".created")));
console.log(hours + " have passed since", getDate($(".created")));
if (hours > 5) {
$(".germ").remove();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr class="pointer">
<td>
<img class="germ" src="~/Image" width="40px" />
<!--
Would advise better format
Example: 2020-04-03T13:00.000-7:00
-->
<i class="created" hidden="hidden">April 3, 2020 13:13:00</i> Document Title
</td>
<td>PDF</td>
<td>March 2020</td>
</tr>
</table>
References
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
How to get the hours difference between two date objects?
Getting the client's timezone offset in JavaScript

AppendChild TypeError even though Child is HTML

I'm using Shopify and am trying to sort blog posts by a different date than the publish date. Shopify Community Forums says the only real way to do it is using liquid to plug in the information and alter it via client side Javascript. I'm doing that by taking the div and the new date and placing it into an object in an array. The object is structured to have a div value and a date value like so:
0:
date: "1563681600"
div: " <div class="article-image">
<a href="/blogs/upcoming/dog-days-of-summer">
<div class="rimage-outer-wrapper" style="max-width: 750px"><div class="rimage-wrapper lazyload--placeholder" style="padding-top:60.0%"><img class="rimage__image lazyload fade-in " data-src="//cdn2.shopify.com/s/files/1/0152/7041/2388/articles/84th_2019-0721_slider_{width}x.jpg?v=1561562008" data-widths="[180, 220, 300, 360, 460, 540, 720, 900, 1080, 1296, 1512, 1728, 2048]" data-aspectratio="1.6666666666666667" data-sizes="auto" alt="DOG DAYS OF SUMMER"><noscript><img src="//cdn2.shopify.com/s/files/1/0152/7041/2388/articles/84th_2019-0721_slider_1024x1024.jpg?v=1561562008" alt="DOG DAYS OF SUMMER" class="rimage__image"></noscript></div></div>
</a>
</div>
<div class="meta">
<span class="meta-item date">1563681600</span>
<span class="meta-item" id="time">1-3pm</span>
<span class="meta-item location">84th Street Location</span>
</div>
<h2>DOG DAYS OF SUMMER</h2>
<div class="rte article-excerpt"><b>Books of Wonder</b><span> </span><span>is excited to host a picture book event: DOG DAYS OF SUMMER. Please join us on Sunday, July 21st at our 84th Street Store to celebrate four amazing picture books about dogs!</span></div>
<p class="fullarticle"><a class="cta-link" href="/blogs/upcoming/dog-days-of-summer">Read more</a></p>
"
The trouble I'm having now after sorting the array by date is how to take all these div elements and display them in the DOM. AppendChild throws an error even though these DIVS are captured using innerHTML. Here is the code:
function storeid() {
var divName = document.getElementsByClassName('pullup');
var className = document.getElementsByClassName('date');
var classnameCount = className.length;
var IdStore = new Array();
for (var j = 0; j < classnameCount; j++) {
var obj = {};
var div = divName[j].innerHTML;
var dateString = className[j].innerText;
obj["div"] = div;
obj["date"] = dateString;
IdStore.push(obj);
}
console.log(IdStore);
IdStore = IdStore.sort(function(a, b) {
return b.date - a.date
});
IdStore.forEach(el => {
document.body.appendChild(el.div);
})
}
storeid();
However despite specifying it only take the div I'm still getting the following error. TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'
Is appendChild not able to append this much? Or is there a better way of solving this?
When you do this:
var div = divName[j].innerHTML;
You're no longer dealing with a Node, it's a string. Remove the .innerHTML from the line and it should work.

Adding media when javascript button is clicked

i have created a JS button that generates random facts when clicked.
now i want each String(fact) to have media below to make the fact more interesting and fun.
<script> <!-- arrays -->function GetValue(){ var myarray= new Array()
myarray[0]="your lungs are worth $58,200 each,heart will fetch $57,000, and your kidneys are good for another $91,400,your DNA will fetch more than 9M$,while your bone marrow, your most valuable possession, is worth $23 million all by itself. Therefore your body market value is exactly: $45,618,575.82."
myarray[1]="Hans Langseth the man with the world's longest beard 5.33 m (17 ft 6 in)tripped on his long beard. He lost his balance and fell, breaking his neck from the unexpected accident! He died instantaneously."
myarray[2]="A Sesame Street episode (ep. 847) was aired on TV in 1976,it was so scary that the authorities had to pull it off due to several complaints from parents saying their children screamed in horror."<!--END-var random = myarray[Math.floor(Math.random() * myarray.length)];//alert(random); document.getElementById("fact button").innerHTML=random;}</script>
HTML:
<input type="button" id="fact_button" value="Fact Button" onclick="GetValue();" />
Assuming you want to show media like images, for instance, this is one way to do it:
window.onload = () => {
const factsArr = [
{
image: 'http://via.placeholder.com/350x150',
content: "your lungs are worth $58,200 each,heart will fetch $57,000, and your kidneys are good for another $91,400,your DNA will fetch more than 9M$,while your bone marrow, your most valuable possession, is worth $23 million all by itself. Therefore your body market value is exactly: $45,618,575.82."
},
{
image: 'http://via.placeholder.com/200x140',
content: "Hans Langseth the man with the world's longest beard 5.33 m (17 ft 6 in)tripped on his long beard. He lost his balance and fell, breaking his neck from the unexpected accident! He died instantaneously."
},
{
image: 'http://via.placeholder.com/200x100',
content: "A Sesame Street episode (ep. 847) was aired on TV in 1976,it was so scary that the authorities had to pull it off due to several complaints from parents saying their children screamed in horror."
}
];
document.getElementById('generate-btn').addEventListener('click', () => {
const idx = Math.floor(Math.random() * factsArr.length);
document.getElementById('random-fact-content').innerHTML = factsArr[idx].content;
document.getElementById('random-fact-image').setAttribute('src', factsArr[idx].image)
})
}
<button id="generate-btn">Generate Random Fact</button>
<div id="random-fact-content"></div>
<img id="random-fact-image"></img>

How to add a class to the element with the closest value [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am making an events calender with dates and would like to add a class to the next upcoming date (the closest to the current date)
html
<div>
<div class=".date" id="9,18,2013">18th Sept 2013: Going Fishing</div>
<div class=".date" id="22,01,2014">22nd Jan 2014: Going on Holiday to Greece</div>
<div class=".date" id="16,02,2014">16th Feb 2014: Business Meeting</div>
<div class=".date" id="27,02,2014">27th Feb 2014: Sisters Birthday</div>
</div>
javascript/jquery
var today = new Date();
var a = $(".date").attr('id')
var b = a.split(",");
var c = new Date(b[2], b[0], b[1]);
this changes the id value as a date but i need to find the closest one to the variable "today"
If the elements are sorted as given in the example then
<div>
<div class="date" id="18,9,2013">18th Sept 2013: Going Fishing</div>
<div class="date" id="22,01,2014">22nd Jan 2014: Going on Holiday to Greece</div>
<div class="date" id="16,02,2014">16th Feb 2014: Business Meeting</div>
<div class="date" id="27,02,2014">27th Feb 2014: Sisters Birthday</div>
</div>
and
var today = new Date();
//clear the time part
today.setHours(0, 0, 0, 0);
//need to remove the . from the class attribute of the elements
$('.date').each(function () {
var parts = this.id.split(",");
var date = new Date(parts[2], parts[1], parts[0]);
if (date - today > 0) {
$(this).addClass('next');
//return false to prevent the iteration of any other element
return false;
}
})
Demo: Fiddle

Categories

Resources