I am creating a web app that allows users to search GIFs using the GIPHY API.
I added code that is supposed to refresh the page, then load all the GIFs.
// the Div where the GIFs from GIPHY will be appended to.
const imagesDiv = document.getElementById("imagesDiv");
// The user input -- the name of GIFs searched. Ex. Cats, Dogs, etc.
const search = document.getElementById("search");
// The search button for GIFs.
const submit = document.getElementById("submit");
// When pressed, it begins searching.
submit.addEventListener("click", function () {
// Refresh page first to get rid of old search results
window.location.reload();
getData(search.value);
});
// Code that uses GIPHY Api
function getData(query) {
// fetch data from GIPHY, using the user's input(ex. dogs) to replace word in the link
fetch(
"https://api.giphy.com/v1/gifs/search?q=" +
query +
"&api_key=8UHgk4rc0ictTp8kMXNGHbeJAWwg19yn&limit=5"
)
.then(function (response) {
return response.json();
})
.then(function (myJson) {
renderData(myJson);
});
function renderData(data) {
console.log(data.data);
// For loop runs as many times as needed to get all GIFs
for (let i = 0; i < data.data.length; i++) {
// create img element to represent the GIFs
const img = document.createElement("img");
// give className for css styling
img.className = "gifs";
// give img url to get the GIFs
img.src = data.data[i].images.original.url;
// put them into a div
imagesDiv.appendChild(img);
}
}
}
Instead it load then refreshes the page, removing all the GIFs before they can pop-up on screen
Your code end at "window.location.reload();".
Now it looks like no chance to execute "getData(search.value);".
Try this,
submit.addEventListener("click", function () {
imagesDiv.innerHTML = "";
getData(search.value);
});
When you reloading page, all of it content including scripts will be reloaded.
So you asked page to reload, and after that trying to load GIFs, this code will try to load GIFs, but reload already started.
The thing you see "it load then refreshes the page" - loaded from cache GIFs, that added to page almost instantly.
You might want to update your code in a way when you just removing elements with GIFs from DOM, and adding a new one.
Instead of
window.location.reload();
you can write:
while (imagesDiv.firstChild) {
imagesDiv.removeChild(imagesDiv.firstChild);
}
Related
I have a Javascript file running on a page and I would like to log certain events as they occur. For example, I have a web store - and when people add an item to their cart, I want to log this event by visiting a page that I built:
function log_event(id) {
window.location.href = 'https://example.com/log/cart.php?id=' + id;
return false;
}
The log/cart.php page doesn't really have anything to display, all it does is insert a record into a database containing the item that was added to the cart, and the date.
The code that calls this function looks like:
document.getElementById('add-to-cart').addEventListener('click', function() {
// Add to the cart
...
// Track the item that was added
let id = document.getElementById('add-to-cart').getAttribute('data-id');
log_event(id);
});
With my current code, the log/cart.php actually replaces the current page. I want the opening of log/cart.php to only happen in the background without the user being interrupted. I don't want it to actually open a browser tab or window and let the user stay in the product page.
You can send an AJAX request to that endpoint:
function log_event(id) {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", 'https://example.com/log/cart.php?id=' + id, true);
xhttp.send();
return false;
}
fetch() can also be used, but be aware of its browser support (no IE).
I am very new to JavaScript. I am trying to make a web application, where a simple back button will go to a specific page I am looking for, one that has the word "search" in it. I don't know the exact URL, because the parameters within that URL change, and I need to keep it consistent to what the user wanted. But this one button should go back to that one page, regardless of the other links that were clicked.
For example:
If I clicked on
Home Page
Main Page
Page 1
Page 1.3
Back
I want the back to always take me to Main Page with the exact parameters it had before, not Home Page.
I tried the following:
The button itself
movieTableBodyElement.append('' + " << Back" + ''); // Building the HTML button, calls the goBackHelper() function
function goBackHelper()
{
// checks if the page directly behind is the Main Page with "search"
if(document.referrer.includes("search"))
{
// if its the main page, exit the function and end recursive call
window.history.go(-1);
}
else
{
// it is not the last page, so go to the past page and check again
window.history.go(-1);
goBackFunction();
}
}
But this takes me to the very first home page. I thought that document.referrer would get me the past URL, but it doesn't seem to be working for me. Is there a way to get the URL from past pages? So if I am on page 2, can I get all the URLs and search for Main Page? Any help is greatly appreciated!
I'm also new to Stack Overflow, so if there is any clarification please don't hesitate to let me know!
document.referrer is not the same as the actual URL in all situations.
Your best bet is to store the URLs in sessionStorage.
Add this snippet of code to your pages:
if (sessionStorage.getItem("locationHistory") !== null) {
var locationHistoryArray = JSON.parse(sessionStorage.getItem("locationHistory"));
locationHistoryArray.push(window.location.href);
sessionStorage.setItem("locationHistory", JSON.stringify(locationHistoryArray));
} else {
var locationHistoryArray = [];
locationHistoryArray.push(window.location.href);
sessionStorage.setItem("locationHistory", JSON.stringify(locationHistoryArray));
}
And this is your goBackHelper() function :
function goBackHelper() {
var searchString = 'search'; //modify this
var locationHistoryArray = JSON.parse(sessionStorage.getItem("locationHistory"));
for (i = 0; i < locationHistoryArray.length; i++) {
if (locationHistoryArray[i].includes(searchString)) {
window.location.assign(locationHistoryArray[i]);
break;
}
}
}
Read about document.referrer here.
First things first: I don't know anything about coding and I basically build my whole HTML file by CMD+C and CMD+V what I found with lots of Google searches and change just what is needed so it fits into what I intended. Interestingly I got a result that is 95% what I wanted.
Now I have just one last thing I can't set (or find about in Google) so hopefully someone can answer it here. [Trying to put in as many information as I can]
I made a simple one page HTML that shows the date/time and plays an audio livestream from my PC when opened.
I also want it to display the "Now Playing" information. After a lot of searches, I finally found a solution that even I could make with Dreamweaver.
I used the "fetch script" (or is it called Fetch APP?) to get a txt file that my music player gives as output with the current song information. That fetch script get the data and put it into a
The problem is that is only seems to do it once at page load and not every few seconds. The contents in the txt change whenever a new song plays and I want the displayed data on the HTML to stay current as well.
So how do I set that fetch script to re-fetch the txt contents every ~10 seconds?
Here is my current fetch script:
<script>
var url = 'NowPlaying.txt';
var storedText;
fetch(url)
.then(function(response) {
response.text().then(function(text) {
storedText = text;
currentSong();
});
});
function currentSong() {
document.getElementById('thesong').textContent = storedText;
}
</script>
For making my HTML I use "Dreamweaver 2019" on "Mac OS 11 Big Sur"
It's a single HTML and all files/assets the HTML accesses (The Audio, Background Images and the TXT file are in the same directory/network)
I hope that provides all necessary details.
Oh and what I tried already is to copy the line "var t = setTimeout(fetch, 100);" into the script, because this seems to be what keeps the clock javascript current and I hoped it would do the same with fetch
Also attached a screenshot of the HTML "live" in chrome >> screenshot
As you can see, the bottom is supposed to have the "Now Playing" information displayed (please ignore that in this example the text is cut to the right, the current information is too long, so it cuts off at the end)
You cam simply use setInterval to call your fetch every 10th seconds.
Just wrap your function in to a function and call that function in setInterval.
=> Also, at sometime if you would like to stop the fetch request on an event like a button click or something you can use clearInterval to stop the fetch request without refreshing the page.
Run snippet below to see the function is getting called every 10th seconds.
var url = 'NowPlaying.txt';
var storedText;
//10 Seconds fetch
function fetch10Seconds() {
//Fetch
fetch(url)
.then(function(response) {
response.text().then(function(text) {
storedText = text;
currentSong();
});
});
console.log('Fetch again in 10 Seconds')
}
//Call function every 10 seconds
setInterval(fetch10Seconds, 10000); // 10 seconds are defined in miliseconds
//Call this on fetch every 10 seconds
function currentSong() {
document.getElementById('thesong').textContent = storedText;
}
You can create a loop using setInterval function
var url = 'NowPlaying.txt';
var storedText;
setInterval(()=>{
fetch(url)
.then(function(response) {
response.text().then(function(text) {
storedText = text;
currentSong();
});
});
},10000) // in miliseconds
function currentSong() {
document.getElementById('thesong').textContent = storedText;
}
Try this:
function doFetch() {
setTimeout(() => {
fetch(url)
.then(response => {
response.text().then(text => {
storedText = text;
currentSong();
doFetch();
});
});
}, 10000);
}
doFetch();
This waits for the data to be fetched before waiting another 10 seconds and fetching again. Using setInterval will get the data every 10 seconds on the dot regardless of the success of the last run of the function.
So I'm trying to redirect the browser to another webpage when the page he is attempting to load matches my conditions (regex). Currently it looks like this: (came up with it here)
function listener(event) {
var channel = event.subject.QueryInterface(Ci.nsIHttpChannel);
var url = event.subject.URI.spec;
if (isToBeRedirected(url)) {
// replace url
}
}
exports.main = function() {
events.on("http-on-modify-request", listener);
}
But the problem is, that this will also replace urls to images for example, which are embedded in the page. My question would be, is there a way of varyfying that the http request is made by typing in a url or clicking a link to a page? So simply everytime a url shows up in the address-bar.
I thought about reading the url of the current tab and comparing it to the request url, but I wasnt able to find out exactly how yet.
I have an idea.
If you do console.log(Ci.nsIHttpChannel) you see it has a bunch of flags, see img at bottom.
So I'm thinking test if it's the main load, meaning its not in a sub frame, but its the whole document of the tab by testing for flag of Ci.nsIHttpChannel.LOAD_INITIAL_DOCUMENT_URI. If its the whole document, its likely from a link, or url bar, or search bar.
So try this:
function listener(event) {
var channel = event.subject.QueryInterface(Ci.nsIHttpChannel);
var url = event.subject.URI.spec;
if (channel.loadFlags & Ci.nsIHttpChannel.LOAD_INITIAL_DOCUMENT_URI) {
//the whole document of the tab is changing
if (isToBeRedirected(url)) {
// replace url
}
}
}
exports.main = function() {
events.on("http-on-modify-request", listener);
}
My other idea, is if you want only url bar changes. Than add an event listener to change of the url bar value. And after change if user hits enter or clicks go, then it register the observer. Then after testing for Ci.nsIHttpChannel.LOAD_INITIAL_DOCUMENT_URI than unregister the observer.
Here's the scenario:
I have a link on "page1.html" that i want to get displayed on an iframe of another link "page2.html" .
How do I do this?
Fourth and final try!
The problem with your page is the following
Your problem is that your link [See adoptable dogs] points to http://hssv.convio.net/PageServer?pagename=adoption_available?http://adopt.hssv.org/search/searchResults.asp?task=search&searchid=&advanced=&s=adoption&animalType=3%2C16&statusID=3&submitbtn=Find+Animals
When I go to
http://hssv.convio.net/PageServer?pagename=adoption_available,
I'm redirected to
http://hssv.convio.net/site/PageServer?pagename=page_not_found
Therefore I assume the correct link is http://hssv.convio.net/site/PageServer?pagename=adoption_available (yup, that loaded a page correctly, you were missing /site/ within the link)
Now the second part of your problem. Your page that contains an iframe expected the name of the page to load into the iframe to be everything after the '?', which was fine before since you were't using any other params in the URL (actually not fine, since it breaks easily)
so your link should be (note that the url passed as a parameter should be url encoded)
http://hssv.convio.net/site/PageServer?pagename=adoption_available&content=http%3A%2F%2Fadopt.hssv.org%2Fsearch%2FsearchResults.asp%3Ftask%3Dsearch%26searchid%3D%26advanced%3D%26s%3Dadoption%26animalType%3D3%2C16%26statusID%3D3%26submitbtn%3DFind%2BAnimals
And your page containing the iframe should modify LoadContent to the following.
function LoadContent() {
var url = getParams()['content'];
if (url) {
LoadIFrame(url);
}
}
function getParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Lastly, I don't want to sound rude, but it seems like you need to do some studying before you are assigned to modify these pages. These are all very basic concepts of HTML, HTTP, and JS. Some debugging would easily identify your problem and it had nothing to do with what you asked initially, it was simply that you modified code without a clue to what it was doing...