I am using a jsnewsticker plugin (http://jsfiddle.net/stevenchu/ezEtK/) which uses <li> to display an item at a time.
The code below works if my <li> items are hard-coded into the HTML. But it doesn't work if I have to dynamically create the <li> items from an RSS feed which my script below does
The final HTML page has the <li> items but the JS isn't scrolling through them. I'm not getting any errors in the console. The JS is appending ticker-active class to my <ul> though.
Could this be a sequential issue - perhaps the JS script is firing before the list of <li> items has been fully rendered? If possible, is there a way I can test this theory?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="/js/jsnewsticker.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.get('http://example.com/feed', function (data) {
var count = 0;
$(data).find("item").each(function () {
var newsfeed = $(this);
var newstitle = newsfeed.find("title").text();
var newslink = newsfeed.find("link").text();
var newslist = '';
if (count < 3) {
newslist += '<li class="newsitem">'
+ '<a href="'
+ newslink
+ '">Latest: '
+ newstitle
+ '</a>'
+ '</li>';
count++;
}
$(".latestnews").append(newslist);
});
});
$('.ticker').Ticker();
});
</script>
The HTML taken from browser source:
<ul class="latestnews ticker ticker-active">
<li class="newsitem">Example</li>
<li class="newsitem">Example</li>
<li class="newsitem">Example</li>
</ul>
You have answered your own question earlier. Yes, you are calling ticker before the async Ajax get call has completed, so it fires up the ticker against an empty list.
You need to call it inside the get. e.g. something like:
<script src="/js/jsnewsticker.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.get('http://example.com/feed', function (data) {
var count = 0;
$(data).find("item").each(function () {
var newsfeed = $(this);
var newstitle = newsfeed.find("title").text();
var newslink = newsfeed.find("link").text();
var newslist = '';
if (count < 3) {
newslist += '<li class="newsitem">'
+ '<a href="'
+ newslink
+ '">Latest: '
+ newstitle
+ '</a>'
+ '</li>';
count++;
}
$(".latestnews").append(newslist);
});
$('.ticker').Ticker();
});
});
</script>
Related
I get some data out of an API. I make two calls to the API and save this output in a variable. Now I have two links - One for Data1 and one for Data2. If I click on Data1, the first call should be loaded. Click on Data2 shows the second call should take place. When someone visits the site, Data1 should be the default displayed dataset.
I have a nearly working solution:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function(){
$("#data1").click(function(e){
e.preventDefault();
var datasets = document.getElementById("datasets");
var html = '';
var i = 0;
var results = <?php echo json_encode($resultsD1) ?>;
for (const result of results) {
html += '<article class="dataset"><span class="title">' + result["title"] + '</span><div class="data-meta">';
html += '<span class="release">' + result["release"] + '</span></div></article>';
i++;
}
products.innerHTML = html;
});
$("#data2").click(function(e){
e.preventDefault();
var datasets = document.getElementById("datasets");
var html = '';
var i = 0;
var results = <?php echo json_encode($resultsD2) ?>;
for (const result of results) {
html += '<article class="dataset"><span class="title">' + result["title"] + '</span><div class="data-meta">';
html += '<span class="release">' + result["release"] + '</span></div></article>';
i++;
}
products.innerHTML = html;
});
});
</script>
Now if I click on Data1 the correct data is loaded. The same when I click on Data2. But how can I make Data1 as default when the site is loaded? Also my code seems so bad constructed. I repeat the whole for loop two times...
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function(){
function setData(dataset_type){
var html = '';
var i = 0;
var products = document.getElementById("datasets");
var results = <?php echo json_encode($resultsD1) ?>;
if(dataset_type == 2){
results = <?php echo json_encode($resultsD2) ?>;
}
for (const result of results) {
html += '<article class="dataset"><span class="title">' + result["title"] + '</span><div class="data-meta">';
html += '<span class="release">' + result["release"] + '</span></div></article>';
i++;
}
products.innerHTML = html;
}
// Default Call onload for dataset 1
setData(1);
$("#data1").click(function(e){
e.preventDefault();
setData(1);
});
$("#data2").click(function(e){
e.preventDefault();
setData(2);
});
});
</script>
You need to add the logic to load the data in function, and call the function on button click as well as on page load.
As per your code, as soon as button is clicked the new data is replacing your old data, do you want to do that or you want to keep old data as it is and append new data? I have added comments in the script as answered for above question
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function loadData(){
var datasets = document.getElementById("datasets");
var html = '';
var i = 0;
var results = <?php echo json_encode($resultsD1) ?>;
for (const result of results) {
html += '<article class="dataset"><span class="title">' + result["title"] + '</span><div class="data-meta">';
html += '<span class="release">' + result["release"] + '</span></div></article>';
i++;
}
//products.append(html); // if you want to append data uncomment this and comment below
products.innerHTML = html; // if you want to replace data comment this and uncomment above
}
$(function(){
// function call on page load
loadData();
$("#data1").click(function(e){
e.preventDefault();
loadData();
});
$("#data2").click(function(e){
e.preventDefault();
var datasets = document.getElementById("datasets");
var html = '';
var i = 0;
var results = <?php echo json_encode($resultsD2) ?>;
for (const result of results) {
html += '<article class="dataset"><span class="title">' + result["title"] + '</span><div class="data-meta">';
html += '<span class="release">' + result["release"] + '</span></div></article>';
i++;
}
products.innerHTML = html;
});
});
</script>
You can create a function
var datasets =document.getElementById("datasets");// make it global
$( window ).load(function() {
loadData(whichButtonCliked,datasets )
});
loadData(whichButtonCliked,datasets )
{
e.preventDefault();
var html = '';
var i = 0;
var results = <?php echo json_encode($resultsD2) ?>;
for (const result of results) {
html += '<article class="dataset"><span class="title">' + result["title"] + '</span><div class="data-meta">';
html += '<span class="release">' + result["release"] + '</span></div></article>';
i++;
}
products.innerHTML = html;
}
and call this function on click now you have to make condition which button is clicked
I am trying to allow clients to create a list of students then view more info by simply clicking on the button with the students name. I've got it to create the button and display the students name in the button but it only calls the function when I click submit to add the student to the list, the actual student button doesn't seem to function.
function updateStudentList() {
var html = "";
for (var i = 0; i < students.length; i++) {
html += "<li><button type='button' class='studentButton'" + "id=" + students[i].name +">" + students[i].name + "</button></li>";
}
$('#studentList').html(html);
for (var i = 0; i < students.length; i++) {
document.getElementById(students[i].name).addEventListener('click', openStudentInfo(students[i].name));
}
}
function openStudentInfo(studentName) {
console.log("Opening " + studentName + " info.");
var studentInfo = requestStudentByName(studentName);
if (studentInfo != null) {
var studentInfoForm = $("#studentInfoForm");
var html = "";
html += "<h3>Student Name: " + studentInfo.name + "</h3>";
html += "<h3>Student ID: " + studentInfo.studentID + "</h3>";
studentInfoForm.html(html);
$("#studentInfoModal").show();
}
}
HTML:
<ul data-role="listview" id="studentList"> </ul>
Note: I can't use the onclick tag in HTML, it causes security issues. Cordova also blocks this.
The way you binding the event is not ok. Try binding this way:
$(document).ready(function() {
$("#studentList").on("click", ".studentButton", function() {
var studentId = $(this).data("studentid");
openStudentInfo(studentId);
});
});
And in your HTML generation:
html += "<li><button type='button' class='studentButton' data-studentid='" + students[i].studentID +"'>" + students[i].name + "</button></li>";
This kind of event delagation works not metter how you create the elements inside the root element(studentList in this case), because the event was bound in it, and not on the dynamic elements.
no jquery version of DontVoteMeDown's answer
document.getElementById('studentList').addEventListener('click', function(event) {
var clickedEl = event.target;
if(clickedEl.className === 'studentButton') {
var studentId = clickedEl.dataset.studentId;
openStudentInfo(studentId);
}
});
I am trying to write some JavaScript code to load JSON from a URL and then display it in a linked listview that navigates to a new panel within the webapp that I am creating. I have successfully rendered the listview from the JSON data however, I cannot seem to get a new panel open. Any ideas? My code so far it below -
<li class="divider">Brown Eyes</li>
<div id="output1"></div>
<li class="divider">Green Eyes</li>
<div id="output2"></div>
<script>
var myContainer = "";
var panel_view = "";
var a = new XMLHttpRequest();
a.open("GET", "https://api.myjson.com/bins/1dwnm", true);
a.onreadystatechange = function () {
console.log(a);
if (a.readyState == 4) {
var obj = JSON.parse(a.responseText);
for (i = 0; i < obj.length; i++) {
if (obj[i].eyeColor == 'brown') {
var myContainer = '<ul class="list"><li><a href="#item_profiles'+i+'" class="icon pin">' + obj[i].name.first + " " + obj[i].name.last + " - " + obj[i].eyeColor + '</li></ul>';
document.getElementById('output1').innerHTML += myContainer;
}
if (obj[i].eyeColor == 'green') {
var myContainer = '<ul class="list"><li><a href="#item_profiles'+i+'" class="icon pin">' + obj[i].name.first + " " + obj[i].name.last + " - " + obj[i].eyeColor + '</li></ul>';
document.getElementById('output2').innerHTML += myContainer;
}
}
}
}
a.send();
panel_view += '<div class="panel" data-title="'+obj[i].name.first+'" id="item_profiles'+i+'" data-footer="none"><img src="http://localhost:3000/uploads/'+obj[i].name.first+'" style="width:100%;height:auto;"><p style="padding-left: 10px; padding-right: 10px;">'+obj[i].name.first+'</p></div>';
$('#profiles_panel').after(panel_view);
</script>
EDITED -
So, the purpose of this is to achieve the below code to use just Native JavaScript as oppose to jQuery. Here is the jQuery version of the code -
<script type="text/javascript">
$(document).ready(function () {
var panel_view_admissions = "";
$.getJSON( 'http://localhost:3000/admissions', function(data) {
$.each( data, function(i, name) {
$('ul.list-admissions').append('<li>'+name.title+'</li>');
panel_view_admissions += '<div class="panel" data-title="'+name.title+'" id="item_admissions'+i+'" data-footer="none"><img src="http://localhost:3000/uploads/'+name.image+'" style="width:100%;height:auto;"><p style="padding-left: 10px; padding-right: 10px;">'+name.content+'</p></div>';
});
$('#admissions_panel').after(panel_view_admissions);
});
});
</script>
I want to append data I fetched from server to a div tag, but I can't get it to work. That's HTML with a div tag to which I'd like to append data from the JS code.
HTML:
<body onload="initialize()">
<div id="text"></div>
</body>
And here is JavaScript code. I would like to replace document.write with a function that will append data to a div tag.
JS:
function initialize() {
$.getJSON('http://www.wawhost.com/izdelava-mobilne-aplikacije-2-del/fetch.php?callback=?', function (data) {
for (var i = 0; i < data.length; i++) {
document.write('<img src="' + data[i].image + '" />' + data[i].title + data[i].description + '<br>');
}
});
}
Fiddle: http://jsfiddle.net/GDxtf/
I just started learning JavaScript. Help will be greatly appreciated :)
Paste this code in the bottom of your HTML document, right before </body>:
<script>
// If you're not using an HTML5 doctype, use <script type="text/javascript> instead of just <script>
$(function () {
$targetDiv = $("#text");
$.getJSON('http://www.wawhost.com/izdelava-mobilne-aplikacije-2-del/fetch.php?callback=?', function (data) {
for (var i = 0; i < data.length; i++) {
var $div = $("<div />");
var $img = $("<img />");
$img.attr("src", data[i].image);
$img.appendTo($div);
var $title = $("<h2>" + data[i].title + "</h2>");
$title.appendTo($div);
var $description = $("<p>" + data[i].description + "</p>");
$description.appendTo($div);
$div.appendTo($targetDiv);
}
});
});
</script>
Did this solve your problem?
I'm a beginner at javascript/jquery and completely new to API's and I'm wondering if anyone could help me with something
What I'm trying to achieve is to have a user enter a keyword/phrase into a textbox, they click search and the page returns a list of people who have that word in their tweet.
I have so far been able to display results from a hard-coded keyword (which I got from a website) but when trying to change it I am getting nothing back.
Here is the working one with hard code
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('http://search.twitter.com/search.json?q=earthquake&lang=en&callback=?', function (data) {
var data = data.results;
var html = "<ul>";
for (var i = 0; i < data.length; i++) {
html += "<li><a href='http://twitter.com/" + data[i].from_user + "'>#"
+ data[i].from_user + "</a>: " + data[i].text + "</li>";
}
html += "</ul>"
$('.content').html(html);
});
});
</script>
<h2>Twitter</h2>
<div class="content">
</div>
And here is the code I'm working on now
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
var button= document.getElementById('searchTwitter');
button.onclick= function(){
var text = document.getElementById('search').value;
}
var baseUrl = "http://search.twitter.com/search";
var query = document.getElementById('<%=searchTwitter.ClientID%>').value;
$(document).ready(function () {
$.ajax({
url: baseUrl + '&text' + '&lang=en&callback=?',
dataType: "jsonp",
success: showResults
});
});
function showResults(data) {
var data = data.results;
var html = "<ul>";
for (var i = 0; i < data.length; i++) {
html += "<li><a href='http://twitter.com/" + data[i].from_user + "'>#"
+ data[i].from_user + "</a>: " + data[i].text + "</li>";
}
html += "</ul>"
$('.content').html(html);
}
</script>
<asp:TextBox ID="search" runat="server"></asp:TextBox>
<asp:Button ID="searchTwitter" runat="server" Text="Button" />
Any help would be much appreciated as I have been trying to find a way to do this for days.
thanks a lot
Here's a working example of what you are describing: http://jsfiddle.net/ZEjey/. You should be able to adapt it to your ASP code.
Relevant code below.
JQuery
$("#SearchButton").click(function() {
$.getJSON('http://search.twitter.com/search.json?q=' + $('#TextSearch').val() + '&lang=en&callback=?', function (data) {
var data = data.results;
var html = "<ul>";
for (var i = 0; i < data.length; i++) {
html += "<li><a href='http://twitter.com/" + data[i].from_user + "'>#"
+ data[i].from_user + "</a>: " + data[i].text + "</li>";
}
html += "</ul>"
$('.content').html(html);
});
});
HTML
<h2>Twitter</h2>
Search for: <input id="TextSearch" type="text" /> <input type="button" id="SearchButton" value="Go" />
<div class="content"></div>
---
EDIT 0
Okay, the code below works. The <asp:Button automatically causes a postback so you don't see anything ever get loaded. You either need to use <input type="button" ... instead or stop the normal events from occurring using event.preventDefault(); as I did below.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Twitter</h2>
<asp:TextBox id="TextSearch" runat ="server"/>
<asp:Button id="SearchButton" runat="server" Text="Search"/>
<div class="content"></div>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" ></script>
<script>
$(document).ready(function () {
$("#SearchButton").click(function () {
event.preventDefault(); // ADD THIS LINE TO YOUR CODE
$('.content').html("<em>loading...<em>");
$.getJSON('http://search.twitter.com/search.json?q=' + $('#TextSearch').val() + '&lang=en&callback=?', function (data) {
var data = data.results;
var html = "<ul>";
for (var i = 0; i < data.length; i++) {
html += "<li><a href='http://twitter.com/" + data[i].from_user + "'>#" + data[i].from_user + "</a>: " + data[i].text + "</li>";
}
html += "</ul>";
$('.content').html(html);
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
});
});
</script>
</form>
</body>
</html>
It looks like you're making an ajax request on document ready, rather than when the button is clicked. I also don't see where you're adding the value from the text box to the query. Here's how you could change your code:
//this code will run when the page loads and set up the button so the
//onclick event executes your function
$(document).ready(function () {
var button = document.getElementById('<%=searchTwitter.ClientID%>');
//you need to make the ajax request in this function, because this
//is fired when the search button is clicked
button.onclick = function() {
var text = document.getElementById('search').value;
var baseUrl = "http://search.twitter.com/search.json";
var query = document.getElementById('<%=search.ClientID%>').value;
$.ajax({
//you're building the request url here, with the text from the
//box as the q parameter
url: baseUrl + '?q=' + query + '&lang=en&callback=?',
dataType: "jsonp",
success: showResults
});
};
});
//this function can be defined outside ready()
function showResults(data) {
var data = data.results;
var html = "<ul>";
for (var i = 0; i < data.length; i++) {
html += "<li><a href='http://twitter.com/" + data[i].from_user + "'>#"
+ data[i].from_user + "</a>: " + data[i].text + "</li>";
}
html += "</ul>";
//I'm assuming you have a div with a content class on your page
$('.content').html(html);
}
You might also want to try out the Chrome developer tools (or Firebug in Firefox). You can set breakpoints and see what's happening at each step. You can also see what requests have been sent and the data returned. That will help give you a better handle on what's going on.