So i want to make a slideshow which takes the pictures out of a folder, instead of hardcoding it.
now i got something like this:
<img class="images" src="slideshow/slide0.png">
<img class="images" src="slideshow/slide1.png">
<img class="images" src="slideshow/slide2.png">
<img class="images" src="slideshow/slide3.png">
<img class="images" src="slideshow/slide4.png">
<img class="images" src="slideshow/slide5.png">
<img class="images" src="slideshow/slide6.png">
<script language='javascript'>
//script voor de slideshow
var myIndex = 0;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("images");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1}
x[myIndex-1].style.display = "block";
setTimeout(carousel, 5000); // Change image every 5 seconds
}
</script>
Als you can see, the images are in the code, but i want them to be taken out of a map, so if i add photos to that map, the slideshow gets longer too. This is to update the slideshow it easier. Since i'm not the one who's gonna use it, they wanted it like this.
i'm not that experienced with javascript, i found this one online but i can understand what it does. an solution with another language can be usefull too! like PHP
You could use AJAX to pull the information from an XML file.
$(function () {
$.ajax({
type: "GET", //call the xml file for reading
url: "Images.xml", //source of the file
dataType: "xml", //type of data in the file
success: parseXml //function to execute when the file is open and ready for use
});
function parseXml(xml) {
var xImages = xml.getElementsByTagName("Image");//Get all nodes tagged "Image" in the xml document.
var maxImages = xImages.length;//Find total number of nodes, for use in the iterations
function fillImages() {
for (i = 0; i < maxHeadlines; i++) {
$("#ImageList").append('<li><img src="' + xImages.childNodes[0].NodeValue[0] + '"</li>');
//one at a time, append the images
}
}
}
HTML
<ul class="ImageList">
</ul>
<!-- This will be populated through the xml - so no <li> elements need to be harcoded in to the page -->
Then you will need an XML file with some <Image> tags
<File>
<Image>file/path/to/image.png</Image>
<Image>file/path/to/image.png</Image>
</File>
This should be enough for you to at least research and implement some AJAX queries into your page.
More information can be found here and here
Update based on OP's comments.
Your XML file markup will look similar to that of your HTML, but the tags are self-governed, in that you create and name them yourself.
You can save your XML, JavaScript, and HTML files all in the same folder, as such
- Web Page (parent folder)
- index.html
- script.js
- Images.xml
This way, the URL for the XML file will simply be "Images.xml"
As for constructing XML documents, it really couldn't be easier.
Say you want a document that contains information about different people
<People>
<Person>
<Name>Greg</Name>
<Age>21</Age>
<Height>6'2"</Height>
</Person>
<Person>
<Name>Sarah</Name>
<Age>45</Age>
<Height>5'5"</Height>
</Person>
<Person>
<Name>Martin</Name>
<Age>80</Age>
<Height>4'11"</Height>
</Person>
</People>
That's all there is to it. You can use it to store any information you want and organise the structure any way you want, with whatever tag names you want to use
This is just somewhere to store the information. The JQuery then opens the file and says "Oh excellent, there's 4 tags here called <Images>, I'll go ahead and pop them in to the page"
This introduction and this how-to guide are very helpful.
It's probably also worth looking here to get an understanding of the syntax rules you need to follow.
There's plenty of information on that website, and it's definitely worth having a browse around and reading up on it all.
Remember Stack Overflow isn't here to do all the work for you, and there should be plenty of information made available here for you to do the appropriate research and implement what it is you want.
Added Code Snippet below, just locate your XML with this and it should work fine -- FOR JQUERY --
BOTH SNIPPETS WORK IF YOU DEFINE THE XML FILE SOMEWHERE / HOSTED OR LOCAL
<!-- XML -->
<whatever>
<image>path/to/file.jpg</image>
<image>path/to/file.jpg</image>
</whatever>
fetch('path/to/xml.xml') // File You want to grab
.then(function(resp) {
return resp.text(); // Response promise function
}).then(function(data) { // data transform function
let parser = new DOMParser(), // Create a parser for DOM
xmlDoc = parser.parseFromString(data, 'text/xml'); // Actually take the text and Convert it to an HTML DOM Element
var xImages = xmlDoc.getElementsByTagName('image')
var maxImages = xImages.length
console.log(xImages.item(0).textContent)
for (i = 0; i < maxImages; i++) {
$(".ImageList").append('<li><img src="' + xImages.item(i).textContent + '"</li>');//one at a time, append the images
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="imglist" class="ImageList">
</ul>
For Vanilla JS i have something else Entirely set up
<!-- XML -->
<whatever>
<image>path/to/file.jpg</image>
<image>path/to/file.jpg</image>
</whatever>
fetch('path/to/xml.xml') // File You want to grab
.then(function(resp) {
return resp.text(); // Response promise function
}).then(function(data) { // data transform function
let parser = new DOMParser(), // Create a parser for DOM
xmlDoc = parser.parseFromString(data, 'text/xml'); // Actually take the text and Convert it to an HTML DOM Element
var xImages = xmlDoc.getElementsByTagName('image')
var maxImages = xImages.length
var liopen = '<li><img src="'
var liclose = '"</li>'
console.log(xImages.item(0).textContent)
for (i = 0; i < maxImages; i++) {
document.querySelector(".ImageList").innerHTML += '<li><img src="' + xImages.item(i).textContent + '"</li>';//Vanilla JS approach to append elements through each iteration
}
})
<ul id="imglist" class="ImageList">
</ul>
Related
I want to add a thumbnail picture to a book's details, derived from the google books api, on the webpage. The code below will place the source code (api) for the appropriate book, first into the text field bookCover and then into the var copyPic, and then it should be copied into imgDisp, but it doesn’t. I can see that bookCover holds the right text, and have checked that copyPic holds the correct content.
<img id="imgDisp" src="http://books.google.com/books/content?
id=YIx0ngEACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api" width="85" height="110"" />
$.getJSON(googleAPI, function(response) {
$("#title").html(response.items[0].volumeInfo.title);
$("#subtitle").html(response.items[0].volumeInfo.subtitle);
$("#author").html(response.items[0].volumeInfo.authors[0]);
$("#description").html(response.items[0].volumeInfo.description);
$("#version").html(response.items[0].volumeInfo.contentVersion);
$("#modeR").html(response.items[0].volumeInfo.readingModes.text);
$("#bookCover").html(response.items[0].volumeInfo.imageLinks.thumbnail);
var copyPic = document.getElementById('bookCover').innerHTML;
document.getElementById("imgDisp").src=copyPic;
Does anyone know why not? Or can I put the api details directly into imgDisp (can’t find such code syntax anywhere on the net)? Everything else is working fine. If I put a src in directly, then it works e.g.
document.getElementById("imgDisp").src = “http://.....api”
but not with a variable.
Without more info - eg, I can't see where the getJSON() function ends or what the URL's are, I can't see what the issue may be (except, perhaps, as in my last comment).
I idea seems ok, as I can replicate it (in a cut-down version of course):
function copyImageSource() {
let d = document.getElementById("bookCover").innerHTML;
document.getElementById("imgDisp").src = d;
}
<button onclick="copyImageSource();">Get image</button>
<div id="bookCover">https://duckduckgo.com/assets/icons/meta/DDG-icon_256x256.png</div>
<img id="imgDisp" src="">
I assume that this is the sort of thing you are trying to achieve?
(javascript -> jquery:
let copyPic = $("#bookCover").html();
$("#imgDisp").attr("src", copyPic);
)
Version using jquery:
function copyImageSource() {
let d = $("#bookCover");
d.html("http://books.google.com/books/content?id=YIx0ngEACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api");
let dCopy = d.html().replace(/&/g, "&");
$("#imgDisp").attr("src", dCopy);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="copyImageSource();">Get image</button>
<div id="bookCover"></div>
<img id="imgDisp" src="https://www.picsearch.com/images/logo.png"/>
If you have jQuery you can easily do the following:
let source = 'https://img.com/image.png';
//to get the image object that has the above just do this:
let img = $('img[src="' + source + '"]');
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'))
How can I pick up image name in html using JavaScript? I searched google and there are some documents about how to get image name on <img> tag,
var filename = tag.replace( /^.*?([^\/]+)\..+?$/, '$1' );
But it return just one name of images. What I'm going to do is get all images name. Imagine the html below,
<html>
<body>
<div class="imagebox">
<img src="/some/path/imageOne.jpg">
<img src="/some/path/imageTwo.jpg">
<img src="/some/path/imageThree.jpg">
</div>
</body>
</html>
after magic, return
imageOne, imageTwo, imageThree. How can I do this..?
Add the following Javascript code at the bottom of your html page :
Solution for browser environment :
var images = document.getElementsByTagName('img');
var images_urls = [];
var images_names = [];
var tmp;
for(var i=0;i < images.length;i++){
images_urls[i] = images[i].getAttribute('src');
tmp = images[i].getAttribute('src').split('/');
images_names[i] = tmp[tmp.length -1].split['.'][0];
}
console.log(images_names); // ["imageOne", "imageTwo", "imageThree"]
and now images_names is an array containing the image names, in this case imageOne,imageTwo and imageThree
Solution for Node.js environment:
lets say you have images url stored in images variable like this :
var images = ["/some/path/imageOne.jpg", "/some/path/imageTwo.jpg", "/some/path/imageThree.jpg"];
you can use Regex, but in this case you can do it easily without using Regex, just split each image url and grab the last part of it, pretty simple, something like this :
var images_names = [];
var tmp
for(var i=0;i < images.length;i++){
tmp = images[i].split('/');
images_names[i] = tmp[tmp.length -1].split['.'][0];
}
console.log(images_names); // ["imageOne", "imageTwo", "imageThree"]
It is the same solution for both Browser and Node.js environment except for the way you get the elements.
Hope this helps.
i am retrieving some information from Google's API and placing them in a single variable, and then inserting them to a div in the DOM like so:
$(function() {
// Load the info via Google's API
$.getJSON("https://www.googleapis.com/plus/v1/people/103039534797695934641/activities/public?maxResults=5&key=AIzaSyBaDZGM-uXuHc-VZZ2DINzVBcIDMN_54zg", function(data) {
// Variable to hold the HTML we'll generate
var html = '';
// how many posts we're displaying on the page
var numberOfPosts = 3;
// Loop over the results, generating the HTML for each <li> item
for (var i=0; i<numberOfPosts; i++) {
html += '<article>';
html += '<img src="'+data.items[i].actor.image.url+'">';
html += '<p>'+data.items[i].title+'</p>';
html += '<p>'+data.items[i].published+'</p>';
html += '</article>';
}
// Insert the generated HTML to the DOM
$('.google-posts-container').html(html);
});
});
My question is: is there a way to store every piece of information in each of its own variable, and then get the information individually by echoing the variable? So i dont have to hardcode all that HTML.
back in the days I would do:
<div id="google-posts-container">
<article>
<img src="{{image}}">
<p>{{title}}</p>
<p>{{published}}</p>
</article>
</div>
<script type="text/javascript">
// render a template (replace variables and return html)
function renderTemplate(tmpl, data){
for (k in data){
while(tmpl.indexOf('{{'+k+'}}') > -1){
tmpl = tmpl.replace('{{'+k+'}}', data[k]);
}
}
return tmpl;
}
$(function(){
// our template
var template = $('#google-posts-container').html();
$('#google-posts-container').html(''); // or clear()
$.getJSON("https://www.googleapis.com/plus/v1/people/103039534797695934641"
+"/activities/public"
+"?maxResults=5&key=AIzaSyBaDZGM-uXuHc-VZZ2DINzVBcIDMN_54zg", function(data) {
// Variable to hold the HTML we'll generate
var html = '';
// how many posts we're displaying on the page
var numberOfPosts = 3;
// Loop over the results, generating the HTML for each <li> item
for (var i=0; i<numberOfPosts; i++) {
html += renderTemplate(template, {
image : data.items[i].actor.image.url,
title : data.items[i].title,
publish : data.items[i].published
});
}
// Insert the generated HTML to the DOM
$('.google-posts-container').html(html);
});
});
</script>
nowadays I use angularjs
About comment by 'galchen' - don't use angular.js for serious &(or) big projects. Just look at source code.
(can't add sub comment, thats why i wrote to main branch)
I'm trying to create a script that will make it easier for users to use a custom button and I have something like
<script src="http://host.com/file.js?id=12345"></script>
What I wonder is how can I, in the file.js get that id parameter.
if I use document, it will get the original html page that has the script line and what I need is that id.
is there any way i can get that id successfully? What should be the scope?
added
the idea is that I can have several buttons in the page for example to have a small and simply list:
<ul>
<li><script src="http://host.com/file.js?id=12345"></script></li>
<li><script src="http://host.com/file.js?id=23456"></script></li>
<li><script src="http://host.com/file.js?id=34567"></script></li>
</ul>
this will ultimately translate to
<ul>
<li><a class="view40btn" href="#" data-id="12345"><strong>V40</strong> Watch the video</a></li>
<li><a class="view40btn" href="#" data-id="23456"><strong>V40</strong> Watch the video</a></li>
<li><a class="view40btn" href="#" data-id="34567"><strong>V40</strong> Watch the video</a></li>
</ul>
the list above will look like this in HTML:
My only issue is that I can't assign the correct id to the data-id attribute as this is generated in the file.js.
result
from Paulpro answer I got it working with his idea and knowing that the client will have much more scripts loaded and several with id's I changed it a bit for the final and working version:
var id = (function(){
var scripts = document.getElementsByTagName('script');
for(var i = 0, result = {}; i < scripts.length; i++)
if(scripts[i].hasAttribute('data-viewfileid'))
result['id'] = decodeURIComponent(scripts[i].getAttribute('data-viewfileid'));
return result['id'];
})();
var html = '<a class="view40btn" href="#" data-id="' + id + '"><strong>V40</strong> Watch the video</a>';
document.write(html);
the script for the user would only be:
<script data-viewfileid="4444" src="file.js" type="text/javascript"></script>
You can get the last script element on the page (which will always be the currently executing one):
var scripts = document.getElementsByTagName('script');
var s = scripts[scripts.length - 1];
Then modify one of the query string parsers from this question to work with that scripts src property:
var url = s.src;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][2]);
}
That will give you an object containing all the query string properties on the current script. You can just access the properties like:
result['id']; // '12345'
In summary
To get the id parameter from within file.js, add the following code to the top of file.js:
var id = (function(){
var scripts = document.getElementsByTagName('script');
var s = scripts[scripts.length - 1];
var qs = s.src.substring(s.src.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][3]);
}
return result['id'];
})();
Make sure it is not in any callback functions like a DOMReady callback.
Edit: You can probably reduce your script to:
var scripts = document.getElementsByTagName('script');
var id = scripts[scripts.length - 1].getAttribute('data-viewfileid');
var html = '<a class="view40btn" href="#" data-id="' + id + '"><strong>V40</strong> Watch the video</a>';
document.write(html);
JavaScript doesn't know anything about the script tag that loaded it. However, there are a few workarounds.
If the file is being preprocessed on the server, you could make the server render the value in the response:
(function() {
var id = <%= params.id %>;
//other stuff here
}());
Or you could give the script tag an id, and make your code find it and pull out the URL.
HTML:
<script src="http://host.com/file.js?id=12345" id="myscript"></script>
JS:
var id = document.getElementById('myscript').split('id=')[1];
Or in modern browsers you could perhaps do something like this to find script tags that match where you know the script is.
var scriptTag = document.querySelector('script[src^="http://host.com/file.js"]');
var id = scriptTag.src.split('id=')[1];
One more solution is to parse .js files with php interpreter. For example in apache configuration:
AddType application/x-httpd-php .js
And in JS:
alert('<?=$_GET["id"]?>');
You can put an ID on anything, including a script tag. So you can do something like this:
HTML:
<script id="myScript" src="http://host.com/file.js?id=12345"></script>
JS:
document.getElementById('myScript').src.split('=')[1]; to get the ID from that particular example string.
If that query string represents a timestamp (in which case you need the latest version) you can modify the JavaScript code to fetch the latest <script> tag like so:
var scripts = document.getElementsByTag('script');
var latestScriptId = scripts[scripts.length-1].src.split('=')[1];
EDIT: In the context of your new edit, you would then take latestScriptId and assign it to the data.id attribute corresponding to the button you would like to create...though again, semantically, it would just make more sense to use HTML's given id attribute, and additionally, since you are not using the href property for the anchor <a> tag, you're better off using a <button> element. So something like this would suffice:
var myButton = document.createElement('button');
myButton.className += 'view40btn';
myButton.id = latestScriptId;
According to your clarifications, what you asking how to do is not what you want to do.
Instead, include one script, and have multiple placeholder nodes.
HTML:
<ul>
<li class="mybutton" data-id="12345"></li>
<li class="mybutton" data-id="23456"></li>
<li class="mybutton" data-id="34567"></li>
</ul>
<script src="myscript.js"></script>
JS:
// myscript.js
var buttons = document.getElementsByClassName('mybutton');
for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
button.innerHTML = "my button html template here with id: "+ button.dataset.id;
}
See it work here: http://jsfiddle.net/zAdnB/
Javascript code does not "realise", that it is a part of some file. JS file is not "executable", there is no main method, which should be run after loading the file. You can not pass GET parameters to it - it is not clear how they should be interpreted.
In your HTML page, you should listen to "onload" method and then call the function from your file with your parameter.