I am in a serious bind. I want to toggle the visibility of some elements I am pulling from an API. The API allows me to make a get request for stories and I am pulling the headlines and images. I can get up to 15 requests at a time from the API. What I want to do is show one request at a time and not all of them at once. When I make the request I get them all at once.
I was thinking of putting the images and headlines into a list and making each child visible one at a time. My jQuery code is below:
var main = function () {
var url = 'http://devapi.xxxxxxx.com/v1/en/stories/latest?format=json&apikey=xxxxxxxxxxxxxxxx';
$.getJSON(url, function(xxxxxx_response) {
//console.log(xxxxx_response);
xxxxxxxxxx_response.stories.forEach(function(data) {
console.log(data);
var $img = $("<img>");
var $p = $("<p>");
$img.attr({
"src": data.largeimage,
"hidden": true,
"id": []
});
$p.attr("hidden", true).append(data.title['#cdata-section']);
$("main .story").append($img, $p);
$("button").click(function(img, p) {
//$img.attr('hidden', false);
//$p.attr('hidden', false);
//s$img.slideToggle('slow');
$img.attr('hidden', false);
$p.attr('hidden', false);
});
});
});
}
$(document).ready(main);
And here is my HTML:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="">
<title>Media on the Move</title>
<style type="text/css">
img {
width: 360px;
heigh: auto;
}
</style>
</head>
<body>
<main>
<button>Next</button>
<div class="story"></div>
</main>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="lib/app.js"></script>
</body>
</html>
Please help!!!
Create your function like this:-
store all the stories in the array, let's suppose story_list and length of story_list in length_story.
Then create an iterative function as follow
function nestedStoryShow(array1 , length1){
//terminating codition
if (length1 == 0){
return;
}
else{
var $img = $("<img>");
var $p = $("<p>");
$img.attr({
"src": array1[array1.length- length1].largeimage,
"id": []
});
$p.append(array1[array1.length- length1].title['#cdata-section']);
$("main .story").append($img, $p);
setTimeout(
function()
{
$img.hide();
$p.hide();
nestedStoryShow(array1 , length1-1);
}, 3000);/*Your Story stays for 3 second and then it is hidden*/
}
}
Attach this function to your button after the ajax call has been successful recieved.
success:function(data){
story_list //array of story
length_story //length
$(button).click(function(){
nestedStoryShow(story_list,length_story);
});
}
Related
I'm new to Javascript and have been spinning on writing this piece of code in order to display a series of pictures on a page from an external source, sort of like an instagram feed, using a GET request through jQuery. I have been given a JSON file that contains an array of image URLs, some of which I want to exclude because they are broken.
Here is the code that I've written thus far - I've tested it and it doesn't work and I'm looking for some guidance on what aspects I may be missing in order to get my code to work:
$(document).ready(function () {
$('imagesFromJSON').click(function () {
$.getJSON("images.json", function (data) {
var arrItems = []; // The array to store JSON items.
$.each(data, function (index, value) {
arrItems.push(value); // Push values in the array.
});
for (let i = 0; i < arrItems.length; i++) {
if (arrItems[i].contains('fakeurl') === false) {
let img = document.createElement('img');
img.src = arrItems[i].Image
document.querySelector('.container').appendChild(image)
}
}
});
});
});
<html>
<head>
<meta charset="UTF-8">
<title>Feed Test</title>
<script type='text/javascript' src='feed.js'></script>
<script src="jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>FEED TEST</h1>
<p><input type="button" id= "imagesFromJSON" value="Show Images" /></p>
<div class="container"></div>
</body>
</html>
Are there any Event Listeners that can be attached to a word. So when the word is clicked, information like a definition can be displayed on the page. Using jQuery
Thanks,
Adam
Sorry for not posting code. I have to make it so that when the user clicks on the name of a person in the list, the box of data on the right side of the screen fills with the description of the location of the artwork. Which is in my JSON file.
Here is my code so far
<!DOCTYPE html>
<hmtl lang="en">
<head>
<meta charset="utf-8" />
<title>AJAX</title>
<link rel="stylesheet" href="styles.css" type="text/css" />
<script src="jquery.js" type="application/javascript"></script>
<script src="ajax.js" type="application/javascript"></script>
</head>
<body>
<div id="loaded-data"></div>
<div id="result-box"></div>
</body>
</hmtl>
$(function() {
let request = $.ajax({
method: 'GET',
url : 'people.json',
dataType: 'json',
});
request.done(function(data) {
let list = data.body.list;
let resultBox = $('#result-box');
let unorderedList = $('<ul>');
resultBox.append(unorderedList);
for (let person of list) {
let listItem = $('<li>');
listItem.text(person.name);
listItem.attr('data-url', person.links[0].href);
unorderedList.append(listItem);
}
});
request.fail(function(response) {
console.log('ERROR: ' + response.statusText);
});
});
{
"links":[{"rel":"self","href":"http://www.philart.net/api/people.json"},{"rel":"parent","href":"http://www.philart.net/api.json"}],
"head":{"title":"People","type":"listnav"},
"body":{
"list":[
{"name":"Adam","links":[{"rel":"self","href":"http://www.philart.net/api/people/325.json"}]},
{"name":"Abigail Adams","links":[{"rel":"self","href":"http://www.philart.net/api/people/157.json"}]},
{"name":"John Adams","links":[{"rel":"self","href":"http://www.philart.net/api/people/410.json"}]},
{"name":"Samuel Adams","links":[{"rel":"self","href":"http://www.philart.net/api/people/439.json"}]},
{"name":"Lin Zexu","links":[{"rel":"self","href":"http://www.philart.net/api/people/347.json"}]},
{"name":"James A. Zimble","links":[{"rel":"self","href":"http://www.philart.net/api/people/345.json"}]},
{"name":"Doris Zimmerman","links":[{"rel":"self","href":"http://www.philart.net/api/people/171.json"}]}
]
}
}
Teemu has already mentioned a way to accomplish this behavior in the comment. You can do it as follows
// handle click and add class
$(".word").click(function() {
var word = $(this).text()
alert(word);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p class="word">Hello</p>
</div>
You could replace the word and wrap it with a div.
$('p').html(function(index, value) {
return value.replace(/\b(here)\b/g, '<div class ="event">here</div>');
});
$('.event').click(function() {
console.log('definition');
});
<p>This is the information: Click here.</p>
This is the code that I want to work out, it's about AMap.com geolocation API. I want to know how to get this value (such as gLats in code) out of the function onComplete().
<!DOCTYPE html>
<html>
<head>
<title>amap</title>
<meta charset="utf-8">
<link rel="stylesheet" href="http://cache.amap.com/lbs/static/main1119.css"/>
<script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=key"></script>
<script type="text/javascript" src="http://cache.amap.com/lbs/static/addToolbar.js"></script>
</head>
<body>
<div id='container'></div>
<div id="tip"></div>
<div id="text"></div>
<div id="txt"></div>
<script type="text/javascript">
var map, geolocation;
map = new AMap.Map("", {
resizeEnable: true
});
map.plugin('AMap.Geolocation', function() {
geolocation = new AMap.Geolocation({
});
map.addControl(geolocation);
geolocation.getCurrentPosition();
AMap.event.addListener(geolocation, 'complete', onComplete);
AMap.event.addListener(geolocation, 'error', onError);
});
function onComplete(data) {
var str=['succsee'];
var gLngs=data.position.getLng();
var gLats=data.position.getLat();
str.push('longitude:' + data.position.getLng());
str.push('latitude:' + data.position.getLat());
document.getElementById('tip').innerHTML = str.join('<br>');
document.getElementById('text').innerHTML = str.join('<br>');
}
function onError(data) {
document.getElementById('tip').innerHTML = 'failure';
}
</script>
</body>
</html>
As I can see, you are already accessing the needed values in onComplete():
str.push('longitude:' + data.position.getLng());
str.push('latitude:' + data.position.getLat());
You cannot simply get them, onComplete is a callback that is called when the values are available. So do anything about them in onComplete, you may want to assingn them to global variables, etc, to have them easyly accessible from anywhere in code.
Assigning them to globals is the way to go.
//declare in the global scope
var gLats = null;
var gLngs = null;
...
function onComplete(data)
{
var str=['success'];
gLats=data.position.getLat();
gLngs=data.position.getLng();
...
}
I've had a look around at 2 or three different ways to do this, however I'm still encountering problems.
With the below I can generate an alert, but nothing gets written to the div
JSON
{
"FixVersion": "Version - 1.2.3",
"BugCount": "27",
"TaskCount": "4",
"StoryCount": "5"
}
JAVASCRIPT ATTEMPT 1
<script type="text/javascript">
function read_project_title() {
$.getJSON("ProjectVersion.json", function(data) {
alert(data["FixVersion"]);
return(data["FixVersion"]);
});
}
</script>
JAVASCRIPT ATTEMPT 2
<script type="text/javascript">
function read_project_title() {
$.getJSON("ProjectVersion.json", function(data) {
var node = document.getElementById('pageTitle');
node.innerHTML(data["FixVersion"]);
});
}
</script>
HTML
<div id="pageTitle"><script>read_project_title();</script></div>
did you tried this way?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="pageTitle"></div>
<script>
function read_project_title() {
$.getJSON("ProjectVersion.json", function(data) {
var node = document.querySelector('#pageTitle');
if (node) {
node.innerHTML = data.FixVersion;
}
});
}
read_project_title();
</script>
</body>
</html>
Try this
<script type="text/javascript">
function read_project_title() {
$.getJSON("ProjectVersion.json", function(data) {
alert(data.FixVersion);
return(data.FixVersion);
});
}
</script>
In your second attempt, simply change the line node.innerHTML(data["FixVersion"]); to:
node.innerHTML = data["FixVersion"];
Hope it helps.
simple fix! just print out all returned data to make sure you're getting what you expect
DEMO
$(function() {
$.getJSON('objects.json',function(data) {
$('#pageTitle').html(data['FixVersion']);
// print data
document.body.innerHTML += JSON.stringify(data, null, 4);
});
});
So I have a website with a Header.html. In the header are three buttons. I've copied the Header.html into all of my other pages with jquery's load. Now what I would like to do is change the colour of one of the buttons depending on the page it's on. But when I use document.GetElementById in javascript it can't find the div of the button I've copied from the Header.html
Here's the Header.html
<div id="Header_Wrapper">
<div id="Header_PageLinksWrapper">
<div class="Header_PageLink">
<a class="Header_PageLinkText" id="PageLink_Games" href="..\Pages\Games.html">Games</a>
</div>
<div class="Header_PageLink">
<a class="Header_PageLinkText" id="PageLink_AboutMe" href="..\Pages\AboutMe.html">About Me</a>
</div>
<div class="Header_PageLink">
<a class="Header_PageLinkText" id="PageLink_CV" href="..\Pages\CV.html">CV</a>
</div>
</div>
</div>
The javascript file:
$(document).ready(
function ()
{
$("#Header").load("..\\Templates\\Header.html");
var filePath = window.location.pathname;
SetPageLinkColours(filePath);
}
);
function SetPageLinkColours(aPath)
{
var firstIndex = aPath.lastIndexOf("/");
var lastIndex = aPath.indexOf(".html");
var id = "PageLink_" + aPath.slice(firstIndex + 1, lastIndex);
var divElement = document.getElementById(id);
if (divElement == null)
{
console.log("Could not find element " + id);
}
divElement.style.color = 0xffffff;
}
One of the pages (eg. Games.html)
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Adabelle Combrink - Games</title>
<link rel="stylesheet" type="text/css" href="..\Templates\Header.css"/>
<link rel="stylesheet" type="text/css" href="..\Templates\Page.css"/>
<link rel="stylesheet" type="text/css" href="..\Pages\Games.css"/>
<script type="text/javascript" src="..\Scripts\jQuery.js"></script>
<script type="text/javascript" src="..\Scripts\Defaults.js"></script>
</head>
<body>
<header>
<div id="Header"></div>
</header>
</body>
</html>
What this gives me in the console is Could not find element PageLink_Games. I don't get that error if I use something that is in Games.html like Header.
Is there any other way of doing the same thing. I know you can include files into eachother with php but I haven't gotten that right and don't seem to be able to run .php files in Visual Studio.
jQuery.load has a success callback. Use it to assure your code is only executed after the loading is complete.
$(document).ready(
function ()
{
$("#Header").load("..\\Templates\\Header.html", null, function() {
var filePath = window.location.pathname;
SetPageLinkColours(filePath);
});
}
);
Also your SetPageLinkColours function can be improved with jQuery:
function SetPageLinkColours(aPath)
{
var firstIndex = aPath.lastIndexOf("/");
var lastIndex = aPath.indexOf(".html");
var id = "PageLink_" + aPath.slice(firstIndex + 1, lastIndex);
var divElement = $("#"+id);
if (!divElement.length)
{
console.log("Could not find element " + id);
}
else
{
divElement.css('color','white');
}
}
load function makes async request , so your code tries to find element before it rely appears. U need to use load function callback http://api.jquery.com/load/
$(document).ready(
function ()
{
$("#Header").load("..\\Templates\\Header.html", function () {
var filePath = window.location.pathname;
SetPageLinkColours(filePath);
});
}
);