I' would like to create Next/Previous buttons for json array, but I can't get it to work.
This is the last one I have tried
<div id="text"></div>
<button name="prev">go to previous div</button>
<button name="next">go to next div</button>
<script>
myFunction([
{
"text": "text0"
},
{
"text": "text1"
},
{
"text": "text2"
},
{
"text": "text3"
}
]);
function myFunction(arr) {
var out = "";
var i ;
out = '<p>' + arr[i].text + '</p> <br>';
document.getElementById("text").innerHTML = out;
}
</script>
You can convert json data to string or better say html with $.each like below. as you tagged jQuery, here is jQuery approach:
myFunction([{
"text": "text0"
},
{
"text": "text1"
},
{
"text": "text2"
},
{
"text": "text3"
}
]);
function myFunction(arr) {
$.each(arr, function(i, v) {
$('#text').append('<div>' + v.text + '</div>');
});
}
var divs = $('.mydivs>div');
var now = 0;
divs.hide().first().show();
$("button[name=next]").click(function(e) {
divs.eq(now).hide();
now = (now + 1 < divs.length) ? now + 1 : 0;
divs.eq(now).show();
});
$("button[name=prev]").click(function(e) {
divs.eq(now).hide();
now = (now > 0) ? now - 1 : divs.length - 1;
divs.eq(now).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text" class="mydivs"></div>
<button name="prev">go to previous div</button>
<button name="next">go to next div</button>
<div id="text">
</div>
<script>
var i = 0;
let arr = [
{
"text": "text0"
},
{
"text": "text1"
},
{
"text": "text2"
},
{
"text": "text3"
}
];
setInterval(function myFunction() {
var out = "";
out = '<p>' + arr[i].text + '</p> <br>';
document.getElementById("text").innerHTML = out;
console.log(out);
if (i < arr.length - 1) {
i += 1;
} else {
i = 0;
}
}, 1000)
</script>
Related
I am currently trying to parse a JSON with JavaScript. My issue is that I'd like the output to look like this:
<li>AppName1</li>
<li>AppName2</li>
<!-- and so on... -->
However it just does not work and I don't know how to achieve that. This is the object deserialized from the JSON response:
{
"data": [{
"AppId": 1,
"AppName": "AppName1",
"AppSize": "2.1"
}, {
"AppId": 2,
"AppName": "AppName2",
"AppSize": ""
}]
}
This is my .js file:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("test").innerHTML = myObj.AppName;
}
};
xmlhttp.open("GET", "json.json", true);
xmlhttp.send();
This is in my HTML file
<p id="test"></p>
Any help would be appreciated as I really cannot seem to understand this a single bit. Thank you so much!
Firstly note that you can only have li elements as children of <ul> or <ol>, so the p element needs to be changed.
The AppName property is part of the objects within data, so you will need to either loop through them:
myObj.data.forEach(function(o) {
document.getElementById("test").innerHTML += '<li>' + o.AppName + '</li>';
}
Or access them, individually by index:
document.getElementById("test").innerHTML = '<li>' + myObj.data[0].AppName + '</li>'; // first item only
var myObj = {
"data": [{
"AppId": 3,
"AppName": "AnimojiStudio",
"AppSlug": "animojistudio",
"AppIcon": "https:\/\/img.lmdinteractive.pro\/icons\/animojistudio.png",
"AppUrl": "https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/animojistudio.ipa",
"AppVersion": "1.2.2",
"AppSize": "2.1"
}, {
"AppId": 2,
"AppName": "Cute Cut Pro",
"AppSlug": "cute-cut-pro",
"AppIcon": "http:\/\/is2.mzstatic.com\/image\/thumb\/Purple118\/v4\/03\/70\/69\/03706968-2399-a1d8-e7c4-12897394ead9\/source\/512x512bb.jpg",
"AppUrl": "https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/cutecutpro.ipa",
"AppVersion": "",
"AppSize": ""
}]
}
document.getElementById("test").innerHTML = '<li>' + myObj.data[0].AppName + '</li>';
<ul id="test"><li>
If you just want a list of the AppName properties, you could do something like the below with jQuery. See the comments in the code for details:
// Below is the JSON string from the OP's link
let json = '{"data":[{"AppId":3,"AppName":"AnimojiStudio","AppSlug":"animojistudio","AppIcon":"https:\/\/img.lmdinteractive.pro\/icons\/animojistudio.png","AppUrl":"https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/animojistudio.ipa","AppVersion":"1.2.2","AppSize":"2.1"},{"AppId":2,"AppName":"Cute Cut Pro","AppSlug":"cute-cut-pro","AppIcon":"http:\/\/is2.mzstatic.com\/image\/thumb\/Purple118\/v4\/03\/70\/69\/03706968-2399-a1d8-e7c4-12897394ead9\/source\/512x512bb.jpg","AppUrl":"https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/cutecutpro.ipa","AppVersion":"","AppSize":""}]}';
// Parse the JSON string into a JS object
json = JSON.parse(json);
let html = "";
// Loop over the object and append a list item for each AppName property.
$.each(json.data, function (index, item) {
html += "<li>" + item.AppName + "</li>";
});
// Append the list to the div.
$("#container").append(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<div id="container"></div>
Using forEach loop and append. Inserting li inside a p tag is not a good idea even though it works. Convert the p into a ul/ol
var data = {
"data": [{
"AppId": 3,
"AppName": "AnimojiStudio",
"AppSlug": "animojistudio",
"AppIcon": "https:\/\/img.lmdinteractive.pro\/icons\/animojistudio.png",
"AppUrl": "https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/animojistudio.ipa",
"AppVersion": "1.2.2",
"AppSize": "2.1"
}, {
"AppId": 2,
"AppName": "Cute Cut Pro",
"AppSlug": "cute-cut-pro",
"AppIcon": "http:\/\/is2.mzstatic.com\/image\/thumb\/Purple118\/v4\/03\/70\/69\/03706968-2399-a1d8-e7c4-12897394ead9\/source\/512x512bb.jpg",
"AppUrl": "https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/cutecutpro.ipa",
"AppVersion": "",
"AppSize": ""
}]
}
data.data.forEach(e =>$('#test').append('<li>' + e.AppName + '</li>' + "<br>"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="test"></ul>
You can use map() since you have an array inside myObj. What you want to do is returning a li with AppName value
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
var ul = document.getElementById("myUl");
var li = document.createElement('li');
var data = myObj.data;
data.map(app => {
li.textContent = app.AppName;
ul.appendChild(li);
})
}
};
xmlhttp.open("GET", "json.json", true);
xmlhttp.send();
You have your object, and it is parsed so let's concentrate on doing something with that object:
var myObj = {
"data": [{
"AppId": 1,
"AppName": "AppName1",
"AppSize": "2.1"
}, {
"AppId": 2,
"AppName": "AppName2",
"AppSize": ""
}]
};
Now we have that, let's use it in different ways. myObj contains an array called data here. That array is an array of JavaScript objects, each with properties like "AppId", "AppName" etc. which we can access either directly or through an index. So, let's put up some examples of how to do that. Comments in the code
var myObj = {
"data": [{
"AppId": 1,
"AppName": "AppName1",
"AppSize": "2.1"
}, {
"AppId": 2,
"AppName": "AppName2",
"AppSize": ""
}]
};
// Here I create a Bootstrap tab and contents
// call to create a new element on the DOM
function additem(item) {
let lt = $('#list-tab');
let ltc = $('#debug-tabContent');
let thing = item.name;
let thingId = "list-" + thing;
let thingTabId = thingId + "-list";
let ttab = $('<a />')
.addClass('list-group-item list-group-item-action')
.data('toggle', "list")
.prop("id", thingTabId)
.attr('role', 'tab')
.prop('href', '#' + thingId)
.html(item.name);
ttab.appendTo(lt);
let lc = $('<div />')
.addClass('tab-pane fade')
.prop("id", thingId)
.attr('role', 'tabpanel')
.text(JSON.stringify(item.obj));
// .text("test");
lc.appendTo(ltc);
}
// * cheat, put the objects in a bootstrap tab content list
additem({
name: "myObj",
obj: myObj
});
additem({
name: "myObjW",
obj: window["myObj"]
});
additem({
name: "data",
obj: myObj.data
});
additem({
name: "data0",
obj: myObj.data[0]
});
additem({
name: "AppName",
obj: myObj.data[0].AppName
});
// pure JS walk
// Here I create a LI list as a Bootstrap list group
let len = myObj.data.length;
let myP = document.getElementById("test");
let myReg = document.getElementById("mylist-reg");
let newUl = document.createElement("ul");
newUl.classList.add('list-group');
newUl.classList.add('list-group-primary');
for (var i = 0; i < len; i++) {
let newLi = document.createElement("li");
let newContent = document.createTextNode(myObj.data[i].AppName);
newLi.appendChild(newContent);
newLi.setAttribute("id", "app-" + myObj.data[i].AppId); //has to be unique
newLi.setAttribute("class", "list-group-item");
newUl.appendChild(newLi);
}
// put the list after the paragraph
document.body.insertBefore(newUl, myP);
let myLast = document.getElementById("app-2");
myLast.classList.add("active");
//activate the bootstrap tab clicks
$('#list-tab').on('click', 'a', function(e) {
e.preventDefault();
$(this).tab('show');
});
// just do it as strings
let html = "";
for (var i = 0; i < len; i++) {
let textel = "<li id='app-js-" + myObj.data[i].AppId + "'>" + myObj.data[i].AppName + "</li>";
html = html + textel;
}
myReg.innerHTML = html;
// jQuery, similar to prior
$.each(myObj.data, function(index, el) {
let textel = "<li id='app-jq-" + el.AppId + "'>" + index + ":" + el.AppName + "</li>";
$('#mylist-jq').append(textel);
});
// jQuery, similar to prior
$.each(myObj.data, function(index, el) {
let elid = 'app-jq2-' + el.AppId;
$("<li />").prop("id", elid).text(el.AppName)
.appendTo('#mylist-jq2');
});
.list-group-item {
border: 1px lime solid
}
.list-item-last {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" />
<ul id="mylist-reg"></ul>
<ul id="mylist-jq"></ul>
<ul id="mylist-jq2"></ul>
<p id="test" class="row">put stuff after here</p>
<div class="row">
<div class="col-4">
<div class="list-group" id="list-tab" role="tablist">
</div>
</div>
<div class="col-8">
<div class="tab-content" id="debug-tabContent">
<div class="tab-pane fade show active" id="list-home" role="tabpanel" aria-labelledby="list-home-list">Click a tab to see one.</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/js/bootstrap.bundle.min.js"></script>
I have an array that should be used to create a list of search engines next to a search field.
I have this script which is working. However, it generates a select box of options - you enter a search phrase, select engine, and then get a result. However, since I have to change the markup to be using Bootstrap, I need to change the select box to an unordered list, like this:
<ul class="dropdown-menu">
<li class="selected">Select</li>
<li>Google</li>
<li>Nyheder</li>
<li>Studier</li>
</ul>
If I try to change the select into <ul id="global_search_filter" class="search_filter"></ul> and var option = jQuery(document.createElement("option")); to var option = jQuery(document.createElement("li"));the scripts breaks.
How can I achieve the same functionality but change the markup from a select box to an unordered list with list options?
I have created a fiddle here.
Maybe someone can point me in the right direction on how to solve this.
el = document.getElementById("localdomain");
el.value = window.location.hostname;
if (!window.searchEngines) {
window.searchEngines = [{
"url": "https://www.google.com",
"label": "Google",
"querykey": "q",
"id": "allWeb"
}, {
"url": "https://www.bing.com",
"label": "Bing",
"querykey": "q",
"id": "bing",
"param": {
"doctype": "",
"path": "",
"cms_mode": ""
}
}, {
"url": "https://www.yahoo.com",
"label": "Yahoo",
"querykey": "q",
"id": "yahoo",
"param": {
"gcse": "014167723083474301078:sxgnobjpld4"
}
}];
}
window.searchCallbacks = [];
jQuery(function() {
var stripPath = function(path) {
return path === "/" ? path : path.replace(/\/$/, "");
};
var isEngineCurrent = function(engine) {
if (stripPath(engine.url) !== stripPath(document.location.origin + document.location.pathname)) {
return false;
}
if (engine.param) {
for (var key in engine.param) {
if (getUrlParameter(key) !== engine.param[key]) {
return false;
}
}
}
return true;
};
var forms = jQuery("form.search_form");
forms.each(function() {
var form = jQuery(this);
var field = form.find("input.search_query");
var filter = form.find(".search_filter");
var resetForm = form.hasClass("search_reset");
if (window.searchEngines) {
for (var i = 0; i < window.searchEngines.length; i++) {
var engine = window.searchEngines[i];
var option = jQuery(document.createElement("option"));
option.text(engine.label);
option.val(i);
if (!resetForm && isEngineCurrent(engine)) {
option.attr("selected", "selected");
field.val(getUrlParameter(engine.querykey));
}
filter.append(option);
}
form.submit(function(event) {
var chosenEngine = window.searchEngines[filter.val()];
form.attr("action", chosenEngine.url);
form.attr("method", chosenEngine.method || "GET");
field.attr("name", chosenEngine.querykey);
if (chosenEngine.param) {
for (var paramName in chosenEngine.param) {
var input = jQuery(document.createElement("input"));
input.attr("type", "hidden");
input.attr("name", paramName);
input.val(chosenEngine.param[paramName]);
form.append(input);
}
}
for (var i = 0; i < window.searchCallbacks.length; i++) {
var callback = window.searchCallbacks[i];
if (jQuery.isFunction(callback)) {
callback(chosenEngine, this);
}
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="global_search_form" class="search_form search_reset" target="_blank">
<input type="text" id="global_search_query" class="search_query" placeholder="Search where...?">
<input id="localdomain" name="localdomain" type="hidden" value=" + window.location.hostname + ">
<select id="global_search_filter" class="search_filter"></select>
<button name="sa" id="submit-button" type="submit">Search</button>
</form>
Working Jsfiddle.
Here is a modified version of your code(unfortunately you can't submit a form on Stack Overflow, but you can test the jsfiddle above). Will update imediatelly with explications:
UPDATE:
Ok, so let's see what we have done here:
First we replace the select with an ul container
We append li elements to the ul parent
We add the data-selected custom attribute on every li element with empty value except the first one which we add the selected value.
We add the data-value attribute to the li element to replicate the value like when we have a select option value.
On click of a dynamically added li element we bind the click event dinamically using event delegation to add the selected attribute value.
On click of the li element we also add the selected value name to the Bootstrap button.
el = document.getElementById("localdomain");
el.value = window.location.hostname;
if (!window.searchEngines) {
window.searchEngines = [{
"url": "https://www.google.com",
"label": "Google",
"querykey": "q",
"id": "allWeb"
}, {
"url": "https://www.bing.com",
"label": "Bing",
"querykey": "q",
"id": "bing",
"param": {
"doctype": "",
"path": "",
"cms_mode": ""
}
}, {
"url": "https://www.yahoo.com",
"label": "Yahoo",
"querykey": "q",
"id": "yahoo",
"param": {
"gcse": "014167723083474301078:sxgnobjpld4"
}
}];
}
window.searchCallbacks = [];
jQuery(function() {
var stripPath = function(path) {
return path === "/" ? path : path.replace(/\/$/, "");
};
var isEngineCurrent = function(engine) {
if (stripPath(engine.url) !== stripPath(document.location.origin + document.location.pathname)) {
return false;
}
if (engine.param) {
for (var key in engine.param) {
if (getUrlParameter(key) !== engine.param[key]) {
return false;
}
}
}
return true;
};
$(document).on('click', 'li', function() {
$('li[data-selected="selected"]').attr('data-selected', '');
$(this).attr('data-selected', 'selected');
$("#menu").text($(this).text());
$("#menu").val($(this).text());
})
var forms = jQuery("form.search_form");
forms.each(function() {
var form = jQuery(this);
var field = form.find("input.search_query");
var filter = form.find(".dropdown-menu");
var resetForm = form.hasClass("search_reset");
if (window.searchEngines) {
for (var i = 0; i < window.searchEngines.length; i++) {
var engine = window.searchEngines[i];
var option = jQuery(document.createElement("li"));
option.text(engine.label);
option.attr('data-value', i);
if (i == 0) {
option.attr('data-selected', 'selected');
} else {
option.attr('data-selected', '');
}
option.attr('role', 'presentation');
if (!resetForm && isEngineCurrent(engine)) {
option.attr("selected", "selected");
field.val(getUrlParameter(engine.querykey));
}
filter.append(option);
}
form.submit(function(event) {
var chosenEngine = window.searchEngines[$('li[data-selected="selected"]').data('value')];
console.log(chosenEngine);
form.attr("action", chosenEngine.url);
form.attr("method", chosenEngine.method || "GET");
field.attr("name", chosenEngine.querykey);
if (chosenEngine.param) {
for (var paramName in chosenEngine.param) {
var input = jQuery(document.createElement("input"));
input.attr("type", "hidden");
input.attr("name", paramName);
input.val(chosenEngine.param[paramName]);
form.append(input);
}
}
for (var i = 0; i < window.searchCallbacks.length; i++) {
var callback = window.searchCallbacks[i];
if (jQuery.isFunction(callback)) {
callback(chosenEngine, this);
}
}
});
}
});
});
li[data-selected="selected"] {
color: #F00;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form id="global_search_form" class="search_form search_reset" target="_blank">
<input type="text" id="global_search_query" class="search_query" placeholder="Search where...?">
<input id="localdomain" name="localdomain" type="hidden" value=" + window.location.hostname +">
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="menu" data-toggle="dropdown">Choose option
<span class="caret"></span></button>
<ul class="dropdown-menu" role="menu" aria-labelledby="menu">
</ul>
</div>
<button name="sa" id="submit-button" type="submit">Search</button>
</form>
var allQuestions = [{
question1: "What is 1 + 1?",
choices: ["1", "2", "3", 4],
correctAnswer: ["2"]
}, {
question2: "What is 2 + 2?",
choices: ["6", "2", "3", 4, ],
correctAnswer: ["4"]
}, {
question3: "What is 3 + 3?",
choices: ["3", "6", "9", 12],
correctAnswer: ["6"]
}];
var newArray = shuffleArray(allQuestions);
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function appendQuestions(number) {
if (newArray == "undefined" || newArray == "null" || newArray.length == 0) {
document.getElementById("questionForm").innerHTML = "Complete!";
} else {
for (i = 0; i < 4; i++) {
$("#questionForm").append("<input name='question' type='radio'>" +
JSON.stringify(newArray[0].choices[i]) + "</input>")
}
}
}
$(function() {
$("#questionList").empty();
appendQuestions();
newArray.shift();
})
function isCorrectAnswer() {
checkedVal = $("input[type=radio][name=question]:checked").val();
if (checkedVal == newArray[0].correctAnswer) {
alert("Correct!");
} else {
alert("Wrong!");
}
alert(checkedVal);
}
$("#submitButton").click(function() {
isCorrectAnswer();
$("#questionForm").empty();
appendQuestions();
newArray.shift();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
<section id='questions'>
<form id="questionForm">
</form>
<div style='clear:both'></div>
<input id='submitButton' type='button' value='Submit'>
</section>
</div>
First off, sorry for the amount of code pasted. I have no idea if I'm missing some small bug or if I'm just writing the wrong code, so I figured it would be best to post all of it.
I am trying to get the value of a radio button. In the isCorrectAnswer function the first 2 lines are to determine the value of the radio button that is currently checked. The problem is when I alert the value of the radio button, it just says "on". I have searched for the last hour trying to figure out what this means or how to fix it and could not find a thing.
I apologize if this is a stupid question or if it has already been answered.
You have to change this line :
$("#questionForm").append("<input name='question' type='radio'>" +
JSON.stringify(newArray[0].choices[i]) + "</input>");
To :
$("#questionForm").append("<input name='question' type='radio' value='" +
JSON.stringify(newArray[0].correctAnswer[i]) + "' />"+JSON.stringify(newArray[0].choices[i]));
Hope this helps.
Fiddle Example
HTML markup:
<div data-id='23|24|25'></div>
<div data-id='29|30|31'></div>
Script:
var array = [
{
"mid": "24"
},
{
"mid": "26"
},
{
"mid": "28"
},
{
"mid": "29"
},
{
"mid": "30"
},
{
"mid": "31"
}
];
var item_html ="";
$.each(array,function(i,k) {
item_html = '<h3>'+k["mid"]+'</h3>';
$('div[data-id="'+k["mid"]+'"').append(item_html); ???????????
});
Would it be possible to find the div element if part of the "|" separated value in its data-id matches the mid?
I'm trying to get an output like this:
<div data-id='23|24|25'>
<h3>24</h3>
</div>
<div data-id='29|30|31'>
<h3>29</h3>
<h3>30</h3>
<h3>31</h3>
You should use the *= selector (contains):
$('div[data-id*="'+k["mid"]+'"').append(item_html);
The result you are looking for is something tricky. I have update your code. hope this will help you.
var array = [
{ "mid": "24"},
{"mid": "26"},
{"mid": "28"},
{"mid": "29"},
{"mid": "30"},
{"mid": "31"}
];
$('[data-id]').each(function(){
var $this = $(this), dataArr = $this.data('id').split('|'), i = 0;
for(;i< dataArr.length; i++) {
if(numInObjArr(array,dataArr[i])) {
$this.append('<h3>'+ dataArr[i] +'</h3>');
}
}
});
//function to check number in array object provided above
function numInObjArr(objArr, num){
for (var i = 0, len=objArr.length; i< len; i++){
if(objArr[i]["mid"] == num) {
return true;
}
}
return false;
}
http://jsfiddle.net/EZ56N/73/ to see the working example
Heres a simple script im using to go through an array displaying a set of html boxes. The initial function echoes a load of elements from a mysql database via php which is then put into the jquery array.
The next3 function works perfectly but for the life of me I cant rewind it to the last three.
Can any one help...
function createTicker(){
tickerItems = new Array();
<?php
for($i = 0; ($rs=mysql_fetch_array($detail4conferences)); $i++) {
$confid = '<a href=\"../'.$rs['confid'].'\" class=\"forthcomingBox\">';
if(!empty($rs['strapline'])){
$strapline = '<span class=\"prefixPages\">'.$rs['strapline'].'</span><br />';
} else {
$strapline = '';
}
$title = '<span class=\"hpTitle\">'.$rs['title'].'</span><br/>';
if(!empty($rs['subtitle'])){
$subtitle = '<span class=\"subtitlePages\">'.$rs['subtitle'].'</span><br />';
} else {
$subtitle = '';
}
$dateline = '<span class=\"dateandlocationPages\">'.$rs['dateline'].'</span></a>';
echo "tickerItems[$i] = '$confid$strapline$title$subtitle$dateline';";
}
?>
i = 0;
tickerIt();
}
function next3(){
if(i >= tickerItems.length){
i = 0;
}
$('#tickerHolder').fadeOut(300, function(){
$('#ticker1').html(tickerItems[i]);
$('#ticker2').html(tickerItems[i+1]);
$('#ticker3').html(tickerItems[i+2]);
$('#tickerHolder').fadeIn("slow");
i = i + 2;
i++;
});
}
I have no idea what to do below - nothing seems to land me on the correct last three no matter what iteration I try...
function prev3(){
if(i >= tickerItems.length){
i = 0;
}
$('#tickerHolder').fadeOut(300, function(){
$('#ticker1').html(tickerItems[i-4]);
$('#ticker2').html(tickerItems[i-5]);
$('#ticker3').html(tickerItems[i-6]);
$('#tickerHolder').fadeIn("slow");
i--;
});
}
Give this a try...
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="line1"></div>
<div class="line2"></div>
<div class="line3"></div>
</div>
<a class="prev">Prev</a>
<a class="next">Next</a>
</body>
<script type="text/javascript">
function showPage(pageNum, arr)
{
$(".container").fadeOut(300, function() {
$(".line1").html("");
$(".line2").html("");
$(".line3").html("");
i = (pageNum - 1) * 3;
$(".line1").html(arr[i]);
$(".line2").html(arr[i + 1]);
$(".line3").html(arr[i + 2]);
$(".container").fadeIn("slow");
});
}
$(function() {
var tickers = [
"Item 1",
"Item 2",
"Item 3",
"Item 4",
"Item 5",
"Item 6",
"Item 7",
"Item 8"
];
var numPages = Math.round(tickers.length / 3);
var currentPage = 1;
showPage(currentPage, tickers);
$(".next").click(function() {
if (currentPage + 1 > numPages) return;
currentPage++;
showPage(currentPage, tickers);
});
$(".prev").click(function() {
if (currentPage - 1 < 1) return;
currentPage--;
showPage(currentPage, tickers);
});
});
</script>
</html>