I'm trying to automate my website by setting predetermined monthly featured videos.
I have JavaScript files already saved w/ the annual data for that particular year - e.g. choose_2017_video.js as well as 2018 & 2019 files. Each image URL text and description text I set in arrays but I can't seem to get them to display. Each array element corresponds to a month [0-11].
The getMonth() method will be the way of retrieving the data.
Somehow, I need to import the song info. into the HTML roughly like this:
<h2 align="center">Video of the month: javascript:song_info[mnth];</h2>
I also need to be able to import the corresponding image path which is saved in a parallel array (of filenames).
var song_info[12], img_URL[12], mnth = today().getMonth();
song_info[7] = "Newsboys - God's Not Dead"; // example data
img_URL[7] = "Newsboys-Gods_Not_Dead_video.JPG";
This site won't let me correctly describe how I'll display the img code using the img_URL element.
Can someone give me examples of how I can import the song information into the h2 code example and img src code?
This might be done a lot easier in an ASP script since I'm more familiar w/ BASIC. JS wasn't even conceived until after I had entered the workforce after a couple yrs. in college.
My intent is to declare new arrays and a pointer variable. The pointer is supposed to determine the month from the current date. One array holds the description of the song while the other holds the filename of the screenshot to be used to launch the YouTube URL in a different browser tab. If I wanted to embed the video, I would just use HTML5 code. It is called by a script src="JSfilename" from an HTML file.
Here is one of the JS files:
var song_info[12], img_URL[12], mnth = today().getMonth();
song_info[0] = "Sidewalk Prophets - Help Me Find It";
song_info[1] = "TobyMac with Kirk Franklin & Mandisa - Lose Your Soul";
song_info[2] = "MercyMe - Dear Younger Me";
song_info[3] = "Kari Jobe - I Am Not Alone";
song_info[4] = "Danny Gokey - Tell Your Heart to Beat Again";
song_info[5] = "Hawk Nelson - Drops In the Ocean";
song_info[6] = "Plumb - Exhale";
song_info[7] = "Newsboys - God's Not Dead";
song_info[8] = "Francesca Battistelli - Holy Spirit";
song_info[9] = "Brandon Heath - Give Me Your Eyes";
song_info[10] = "Matthew West - Strong Enough";
song_info[11] = "Jordan Feliz - The River";
img_URL[0] = "Sidewalk_Prophets-Help_Me_Find_It_video.png";
img_URL[1] = "TobyMac-LoseMySoul_video.png";
img_URL[2] = "MercyMe-DearYoungerMe_video.png";
img_URL[3] = "KariJobe-IAmNotAlone_video.png";
img_URL[4] = "DannyGokey-TellYourHeartToBeatAgain_video3.PNG";
img_URL[5] = "HawkNelson-DropsInTheOcean_video.PNG";
img_URL[6] = "Plumb-Exhale_video.PNG";
img_URL[7] = "Newsboys-Gods_Not_Dead_video.JPG";
img_URL[8] = "FrancescaBattistelli-HolySpirit_video.JPG";
img_URL[9] = "BrandonHeath-GiveMeYourEyes_video.JPG";
img_URL[10] = "Matthew_West-StrongEnough_video.JPG";
img_URL[11] = "JordanFeliz-TheRiver_video.PNG";
So to be clear, you want something like
<h2 align="center">Video of the month: {your_random_video_name_from_your_JSFile}</h2>
So why not just doing this :
<h2 align="center" id="video_name">Video of the month:</h2>
<img src="#" alt="" id="video_preview"/>
<script>
var today = new Date();
var song_info = new Array, img_URL = new Array, mnth = today.getMonth();
song_info[9] = "CHVRCHES - Leave A Trace"; // example data
img_URL[9] = "http://diymag.com/media/img/Artists/C/Chvrches/October-cover/_1500x1000_crop_center-center_75/chvrches-mike-massaro-diy-2015-05.jpg";
song_info[10] = "Newsboys - God's Not Dead"; // example data
img_URL[10] = "Newsboys-Gods_Not_Dead_video.JPG";
document.getElementById("video_name").insertAdjacentHTML('beforeend',song_info[mnth]);
var image = document.getElementById("video_preview");
image.src = img_URL[mnth];
</script>
Example JSFiddle
Related
I'm wondering how to extract images from RSS and Atom feeds so I can use them as a thumbnail when display the feed in a container with it's relative Title, Description and Link. So far my code, (shown below), grabs images from only certain feed types, I'm wondering how I can grab every image my script comes across.
if (feed_image_type == "description") {
item_img = $($(this).find('description').text()).find("img").attr("src");
} else if (feed_image_type == "encoded") {
item_img = $($(this).find('encoded').text()).find("img").attr("src");
} else if (feed_image_type == "thumbnail") {
item_img = $(this).find('thumbnail').attr('url');
} else {
item_img = $(this).find('enclosure').attr('url');
}
For example, I cannot figure out how I would grab the image link from the code rss feed snippet below:
<description>
<![CDATA[
<img src="https://i.kinja-img.com/gawker-media/image/upload/s--E93LuLOd--/c_fit,fl_progressive,q_80,w_636/hd6cujrvf1d72sbxsbnr.jpg" /><p>With a surprise showing of skill and, at one point, a miracle, the bottom-ranked team in the European <em>League </em>Championship Series will not end the summer winless.<br></p><p>Read more...</p>
]]>
</description>
Using these sources:
parse html inside cdata using jquery or javascript
jQuery.parseXML
https://www.w3schools.com/xml/dom_cdatasection.asp
It is essential that you get your content correctly as XML, by setting the dataType to 'xml'.
This code is self-contained and works:
var xmlString = '<Customer><![CDATA[ <img src="y1" /> ]]></Customer>';
var xmlObj = $.parseXML(xmlString);
var cdataText = xmlObj.firstChild.firstChild.textContent;
var jqueryObj = $(cdataText);
var imgUrl = jqueryObj.find('img').attr('src');
console.log(imgUrl);
This is slightly imprecise because you don't give quite enough information to exactly reproduce your situation. I will start as though this from your question is the only part of your code:
if (feed_image_type == "description") {
item_img = $($(this).find('description').text()).find("img").attr("src");
}
This ought to get close:
if (feed_image_type == "description") {
var cdataText = $(this).firstChild.firstChild.textContent;
var jqueryObj = $(cdataText);
item_img = jqueryObj.find('img').attr('src');
}
You can also try this.
let str = `<description>
<![CDATA[
<img src="https://i.kinja-img.com/gawker-media/image/upload/s--E93LuLOd--/c_fit,fl_progressive,q_80,w_636/hd6cujrvf1d72sbxsbnr.jpg" /><p>With a surprise showing of skill and, at one point, a miracle, the bottom-ranked team in the European <em>League </em>Championship Series will not end the summer winless.<br></p><p>Read more...</p>
]]>
</description>`;
//We need to strip CDATA in our case. Otherwise the parser will not parse the contents inside it.
str = str.replace("<![CDATA[", "").replace("]]>", "")
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(str,"text/xml");
let images = [...xmlDoc.querySelectorAll('img')].map(image=>image.getAttribute('src'))
I'm building a little webpage to list the outstanding assignments I have at college.
Here's the code:
<div class="assignment">
<div class="itemt green">DUE: 28/03/2014</div>
</div>
Here's the actual page: www.edavies.co/wkc
I would like the class green to be used if before the due date, the class amber for two weeks before the due date and finally the class red for one week before. If possible it would be cool to have black on the due date and afterwards.
Hope this makes sense. Anything is fine, PHP, JavaScript, jQuery.
check http://jsfiddle.net/NhmW7/, test it changing those dates.
the function i made for this problem.
$( ".itemt" ).each(function() {
var text=$(this).text();
var res = text.split(" ");
var resta = res[1].split("/");
var dd=resta[0];
var mm=resta[1];
var yy=resta[2]; // i couldnt test with dd/mm/yyy format, so i changed to mm/dd/yyy
var now = new Date(); //"now"
var duedate = new Date(mm+'/'+dd+'/'+yy) // due date
var diff = Math.abs(now-duedate);
var each_day = 1000 * 60 * 60 * 24;//milliseconds in a day
var days = Math.round(diff / each_day);
if(days <= 14)
$(this).removeClass("green").addClass("amber");
if(days <= 7)
$(this).removeClass("amber").addClass("red");
if(days > 14)
$(this).addClass("green");
});
As you can use PHP it would be simple.
Add a placeholder in your html
<div class="item color_by_date_id1">DUE: 28/03/2014</div>
Then you parse the page on the request, replace the placeholder with a class name based on today's date and the date intervals for the particular placeholder, which could be stored in a server side config file or better, together with the items themselves.
The actual coding I am sure you can fix, after building the site already :)
I would go with the following route:
Store your assignments in a JSON array
{
"assignments": [
{
"name": "Assignment 1",
"dueDate": "11/03/2014"
},
{
"name": "Assignment 2",
"dueDate": "11/04/2014"
},
{
"name": "Assignment 3",
"dueDate": "11/07/2014"
}
]
}
Look into Handlebars, Mustache works too
Build a template and add some custom helper functions (tutorials on Handlebars) to alter the class depending on the dueDate
You could use Javascript for this. A solution with jquery should be something like adding the code below:
<script type="text/javascript">
$(document).ready(function(){
var dueDate = new Date(2014,3, 28);
var today = new Date();
if (today>= dueDate){
// or other conditions
$(".itemt").addClass("expired");
}else{
$(".itemt").addClass("expired");
}
});
</script>
This is the idea - you can manage the css class by comparing the date in javascript. Good luck!
I have a list of airport codes, names, and locations in an Excel Spreadsheet like the below:
+-------+----------------------------------------+-------------------+
| Code | Airport Name | Location |
+-------+----------------------------------------+-------------------+
| AUA | Queen Beatrix International Airport | Oranjestad, Aruba|
+-------+----------------------------------------+-------------------+
My Javascript is passed a 3 character string that should be an airline code. When that happens I need to find the code on the spreadsheet and return the Airport Name and Location.
Im thinking something like:
var code = "AUA";
console.log(getAirportInfo(code));
function getAirportInfo(code) {
// get information from spreadsheet
//format info (no help needed there)
return airportInfo;
}
Where the log would write out:
Oranjestad, Aruba (AUA): Queen Beatrix International Airport
What is the easiest method to get the data I need from the spreadsheet?
Extra Info:
The spreadsheet has over 17,000 entries
The function alluded to above may be called up to 8 times in row
I don't have to use an Excel Spreadsheet thats just what I have now
I will never need to edit the spreadsheet with my code
I did search around the web but everything I could find was much more complicated than what Im trying to do so it made it hard to understand what Im looking for.
Thank you for any help pointing me in the right direction.
I ended up using a tool at shancarter.com/data_converter to convert my flie to a JSON file and linked that to my page. Now I just loop through that JSON object to get what I need. This seemed like the simplest way for my particular needs.
I've used a plain text file(csv, or tsv both of which can be exported directly from Excel)
Loaded that into a string var via xmlhttprequest. Usually the browsers cache will stop having to download the file on each page load.
Then have a Regex parse out the values as needed.
All without using any third party....I can dig the code out if you wish.
Example:
you will need to have the data.txt file in the same web folder as this page, or update the paths...
<html>
<head>
<script>
var fileName = "data.txt";
var data = "";
req = new XMLHttpRequest();
req.open("GET", fileName, false);
req.addEventListener("readystatechange", function (e) {
data = req.responseText ;
});
req.send();
function getInfoByCode(c){
if( data == "" ){
return 'DataNotReady' ;
} else {
var rx = new RegExp( "^(" + c + ")\\s+\\|\\s+(.+)\\s+\\|\\s+\\s+(.+)\\|", 'm' ) ;
var values = data.match(rx,'m');
return { airport:values[2] , city:values[3] };
}
}
function clickButton(){
var e = document.getElementById("code");
var ret = getInfoByCode(e.value);
var res = document.getElementById("res");
res.innerText = "Airport:" + ret.airport + " in " + ret.city;
}
</script>
</head>
<body>
<input id="code" value="AUA">
<button onclick="clickButton();">Find</button>
<div id="res">
</div>
</body>
</html>
I have a web page that asks the user for a paragraph of text, then performs some operation on it. To demo it to lazy users, I'd like to add an "I feel lucky" button that will grab some random text from Wikipedia and populate the inputs.
How can I use Javascript to fetch a sequence of text from a random Wikipedia article?
I found some examples of fetching and parsing articles using the Wikipedia API, but they tend to be server side. I'm looking for a solution that runs entirely from the client and doesn't get scuppered by same origin policy.
Note random gibberish is not sufficient; I need human-readable sentences that make sense.
My answer builds on the technique suggested here.
The tricky part is formulating the correct query string:
http://en.wikipedia.org/w/api.php?action=query&generator=random&prop=extracts&exchars=500&format=json&callback=onWikipedia
generator=random selects a random page
prop=extracts and exchars=500 retrieves a 500 character extract
format=json returns JSON-formatted data
callback= causes that data to be wrapped in a function call so it can be treated like any other <script> and injected into your page (see JSONP), thus bypassing cross-domain barriers.
requestid can optionally be added, with a new value each time, to avoid stale results from the browser cache (required in IE9)
The page served by the query is something that looks like this (I've added whitespace for readability):
onWikipedia(
{"query":
{"pages":
{"12362520":
{"pageid":12362520,
"ns":0,
"title":"Power Building",
"extract":"<p>The <b>Power Building<\/b> is a historic commercial building in
the downtown of Cincinnati, Ohio, United States. Built in 1903, it
was designed by Harry Hake. It was listed on the National Register
of Historic Places on March 5, 1999. One week later, a group of
buildings in the northeastern section of downtown was named a
historic district, the Cincinnati East Manufacturing and Warehouse
District; the Power Building is one of the district's contributing
properties.<\/p>\n<h2> Notes<\/h2>"
} } } }
)
Of course you'll get a different article each time.
Here's a full, working example which you can try out on JSBin.
<HTML><BODY>
<p><textarea id="textbox" style="width:350px; height:150px"></textarea></p>
<p><button type="button" id="button" onclick="startFetch(100, 500)">
Fetch random Wikipedia extract</button></p>
<script type="text/javascript">
var textbox = document.getElementById("textbox");
var button = document.getElementById("button");
var tempscript = null, minchars, maxchars, attempts;
function startFetch(minimumCharacters, maximumCharacters, isRetry) {
if (tempscript) return; // a fetch is already in progress
if (!isRetry) {
attempts = 0;
minchars = minimumCharacters; // save params in case retry needed
maxchars = maximumCharacters;
button.disabled = true;
button.style.cursor = "wait";
}
tempscript = document.createElement("script");
tempscript.type = "text/javascript";
tempscript.id = "tempscript";
tempscript.src = "http://en.wikipedia.org/w/api.php"
+ "?action=query&generator=random&prop=extracts"
+ "&exchars="+maxchars+"&format=json&callback=onFetchComplete&requestid="
+ Math.floor(Math.random()*999999).toString();
document.body.appendChild(tempscript);
// onFetchComplete invoked when finished
}
function onFetchComplete(data) {
document.body.removeChild(tempscript);
tempscript = null
var s = getFirstProp(data.query.pages).extract;
s = htmlDecode(stripTags(s));
if (s.length > minchars || attempts++ > 5) {
textbox.value = s;
button.disabled = false;
button.style.cursor = "auto";
} else {
startFetch(0, 0, true); // retry
}
}
function getFirstProp(obj) {
for (var i in obj) return obj[i];
}
// This next bit borrowed from Prototype / hacked together
// You may want to replace with something more robust
function stripTags(s) {
return s.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, "");
}
function htmlDecode(input){
var e = document.createElement("div");
e.innerHTML = input;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
</script>
</BODY></HTML>
One downside of generator=random is you often get talk pages or generated content that are not actual articles. If anyone can improve the query string to limit it to quality articles, that would be great!
hope someone can help a noob. Many thanks in advance.
I have an index page with links to hundreds of other pages holding song words.
I have built each song page but it would be MUCH simpler to have one MASTER page that took a variable from the index page and found the corresponding words (which exist as png graphics.)
I have sorted Step 1 - I can pass a variable from the index page to the master page using:
<a href="javascript: window.open('MUSIC/beatles/mastertest2.html?song=ER', '_parent')">
where song=ER is the variable to display the words for Eleanor Rigby. For Step 2, I can also retrieve that information in the master page with:
var imageSrc = (qs("song")+".png"); document.write(imageSrc);
which will display the text ER.png which is the name of the image I want to display.
For Step 3 I am trying to get this same variable read into:
<input type="image" src="imageSrc;">
to display the picture. I have searched this and other forums for days now and nothing suggested works for me. I could be missing out an essential early step in the coding?
Update:
My master html file has this code to retrieve the variable:
function qs(search_for) {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0 && search_for == parms[i].substring(0,pos)) {
return parms[i].substring(pos+1);;
}
}
return "";
}
And it uses this code to disply the variable (appended with .png) just to prove to me that it is getting through:
var imageSrc = (qs("song")+".png");
document.write(imageSrc);
Then I am trying to feed the variable into a routine to display the png selected. The next script doesn't work but I am thrashing about trying anything right now:
var imageSrc = (qs("song")+".png");
document.write(imageSrc);
<input type="image" src="#imageSrc;" border="0" value="Notes" onClick="placeIt(); showIt()">
<input id="song-image" type="image">
var imageSrc = 'ER.png';
var input = document.getElementById('song-image');
input.src = imageSrc;
If you have already <input type="image"> in your HTML page, you must add an id and then set it's src attribute with
HTML:
<input id="song-image" type="image">
JS:
var imageSrc = 'http://www.lorempixel.com/200/100';
var input = document.getElementById('song-image');
input.src = imageSrc;
JSFiddle for testing.
If I understood you right, its very simple. Are you looking for this?
var input = document.createElement('input');
input.type = 'image';
input.src = imageSrc;
document.body.appendChild(input);
If you can print the variable imageSrc using document.write, then you can use it like shown above.