how can i update content in marquee every 20 second using javascript?
i mean , in the first 20 seconds he reads the first object , on second 40 reads the second object and so on .. , without updating the page , mean update it automatically
this is the javascript function :
function read () {
$.getJSON("jsons/jobs.json", function(json) {
Thejobs = json;
for(var k in Thejobs.Studies){
$('#boxContent').append('<br>'+"position: "+Thejobs.Studies[k].position+
'<br>'+"Academy: "+Thejobs.Studies[k].academy+'<br>'+"address: "
+Thejobs.Studies[k].address+'<br>'+"Description: "+Thejobs.Studies[k].jobDescription)
$('#boxContent').append("<br>_____________________");
}}); }
this is my json file :
{"Studies": {
"jobID1": {
"position": "student position",
"academy": "Haifa University",
"address": "haifa,isreal",
"jobDescription": "Big data"
},
"jobID2": {
"position": "Research 1",
"academy": "saarland University",
"address": "saarbrucken , germany",
"jobDescription": "Electronic engineer"
},
"jobID3": {
"position": "Studie 1",
"academy": "Technion",
"address": "haifa,isreal",
"jobDescription": "Speed of internet"
},
"jobID4": {
"position": "Studie 2",
"academy": "Technion",
"address": "USA ,los angeles",
"jobDescription": "analysis data "
}
}
}
html file :
<marquee direction="up" scrollamount="2">
<p id="boxContent"></p>
</marquee>
i've tried this but didn't work:
<script>
var myVar = setInterval(joobs(), 20000);
var ii=0;
function joobs(){
$.getJSON("jsons/jobs.json", function(json) {
Thejobs = json;
$('#boxContent').append('<br>'+"position:
"+Thejobs.Studies[ii].position+
'<br>'+"Academy: "+Thejobs.Studies[ii].academy+'<br>'+"address: "
+Thejobs.Studies[ii].address+'<br>'+"Description:
"+Thejobs.Studies[ii].jobDescription)
$('#boxContent').append("<br>_____________________");
});
ii=ii+1;
</script>
I couldn't resist making this abomination.
If you need to do something at a regular interval, use setInterval. Which has the signature setInterval(callback_function, interval_in_milliseconds); Just put your function to change the value of the marquee as the callback and set the interval to 20000 to delay for 20 seconds. Your function will be called every 20 seconds like in my following example.
var values = ["Marquees", "shall", "never", "die.", "Long", "live", "the", "marquee!"];
var iterator = 1;
var colorator = 0;
function updateMarquee() {
document.getElementById('boxContent').innerHTML = values[iterator];
iterator = (iterator + 1) % values.length;
console.log("updateMarquee() has been called");
return function() {
console.log("updateMarquee() return value was called instead of the function");
};
}
setInterval(updateMarquee, 1000);
setInterval(updateMarquee(), 10000);
<marquee direction="right" scrollamount="10" behavior="alternate">
<p id="boxContent">Marquees</p>
</marquee>
Update: In regard to user78403's answer, I've updated my code snippet to show the difference between calling the function itself in a setInterval and calling a functions return value. In the example you will see updateMarquee() has been called logged every second because of the line setInterval(updateMarquee, 1000);. But you will also see updateMarquee() return value was called instead of the function logged every 10 seconds because of the line setInterval(updateMarquee(), 10000);
P.S. Don't use a marquee. Having anything automatically moving, playing, changing on a website might have been mind-blowing 20 years ago, but now its just annoying and users will look down on your site for it. You should just have a static list of your job offerings that users can read through at their own pace.
I corrected a few syntax errors in your code. I'll explain the most important things I've done:
setInterval(joobs(), 20000) -> setInterval(joobs, 20000): You have to
pass the method itself as argument. Else the method will be called
and its return value will be executed every 20 seconds.
Thejobs.Studies[ii] -> Thejobs.Studies["jobID" + ii]: Give the property name as index. Passing a number doesn't work. It is also necessary to initialize ii with 1 instead of 0 because of the JSON file's property names.
I also added some missing brackets.
HTML and JSON aren't changed.
So it all looks like this:
var myVar = setInterval(joobs, 20000);
var ii=1;
function joobs() {
$.getJSON("jsons/jobs.json", function (json) {
var Thejobs = json;
$('#boxContent').append('<br>' + "position:" +
Thejobs.Studies["jobID" + ii].position +
'<br>' +
"Academy: " +
Thejobs.Studies["jobID" + ii].academy +
'<br>' +
"address: " +
Thejobs.Studies["jobID" + ii].address +
'<br>' +
"Description:" +
Thejobs.Studies["jobID" + ii].jobDescription);
$('#boxContent').append("<br>_____________________");
});
ii = ii + 1;
}
Related
I'm trying to create dynamic popovers that are generated from a 'dictionary' array that injects HTML into existing text on the page. The code was initially uses for tooltips and worked well but now I am trying to transfer over to popovers. However the html isn't injecting and I'm stuck with it. The aim is to click on a word and have the definition etc popup. I also have a standard popover on the same page that functions correctly. I'm not getting any errors in the console :(
//script.js
$(function() {
var $words = [
{
word: "ね",
kana: "",
romaji: "ne",
definition: "n postposition<br>indicates emphasis, agreement, request for confirmation, etc., is it so, hey, come on, listen, not",
note: ""
},
{
word: " 動画",
kana: "どうが",
romaji: "douga",
definition: "video, movie, moving picture, animation, animated cartoon, in-betweens (animation)",
note: ""
},
{
word: " 今日",
kana: "きょう",
romaji: "kyou",
definition: "adjective today, this day, these days, recently, nowadays",
note: ""
},
{
word: "毎日",
kana: "まいにち",
romaji: "mainichi",
definition: "every day",
note: ""
},
{
word: "も",
kana: "",
romaji: "mo",
definition: "adjective today, this day, these days, recently, nowadays",
note: " te form"
},
{
word: "頑張りましょう",
kana: "がんばりましょう",
romaji: "ganbarimashou",
definition: "verb to persevere, to persist, to keep at it, to hang on, to hold out, to do one\'s best",
note: "lets do"
},
];
$('.define').definitions({
term: $words
});
}); //end $(function()
$(document).ready(function() {
$('[data-toggle="popover"]').popover();
});
/*==================js/jquery.define.js============================*/
var html;
$.fn.definitions = function(words) {
//$.fn alias for jQuery.prototype extends jQuery with your own functions
//console.log("words: ", words); // returns words array
var count = 0;
// Iterate over a jQuery object, executing a function for each matched element.
return this.each(function() {
var _results = [];
var _term = words["term"]; //console.log(_term); //return each definition / word pair object in a single array
var _this = $(this); //console.log(_this);
if (_term.length > 1) {
$.each(_term, function() {
for (let key in _term) {
// iterates over all properties of an object returning value only.
var val = _term[key]; //console.log(val); //returns each dict def / word pair object individually
_results.push(
_this.html(function(index, htmlContent) {
if (
_this
.text()
.toUpperCase()
.indexOf(val["word"].toUpperCase()) >= 0
) {
//console.log(html);
return (html = define_replace(
val["word"],
val["definition"],
val["kana"],
val["romaji"],
val["note"],
htmlContent,
key
)); //html injecting
}
})
);
} //end for...in
});
$("#japanese").html(html); //changed from .text()
} else {
_results.push(
_this.html(function(index, htmlContent) {
if (
_this
.text()
.toUpperCase()
.indexOf(_term["word"].toUpperCase()) >= 0
) {
return (html = define_replace(
_term["word"],
_term["definition"],
_term["kana"],
_term["romaji"],
htmlContent
));
}
})
);
}
}); //end return this.each(function()
}; //end $.fn.definitions
//inject class before and after found word in html
var define_replace = function(word, def, kan, rom, note, html, key) {
//console.log(arguments);
return html.replace(
'<a data-html="true" data-toggle="popover" title="Popover - title" data-content="' + def + '>' + word + " " + '</a>', "gi"
); //html building - replace word + space with html
(n - adv, n, ctr) time;
hours;
(P) < /span></span >
}; // end define_replace
//index.html
<div class="define">
<p id="japanese">ね 、 毎日 動画 今日 も 頑張りましょう</p>
</div>
include popper.min.js before bootstrap.js or use bootstrap.bundle.min.js and Enable popovers everywhere
$(function () {
$('[data-toggle="popover"]').popover()
})
uncaught TypeError: cannot set property "innerHTML" of null
at populate (app.js:13)
at app.js:55
I entered this code watching a video on youtube from beginning to end:
https://www.youtube.com/watch?v=jvk1pFNqXaw&t=293s
heres a link to my repo with everything you'll need to copy, paste, run to see what im facing right now:
function populate() {
if(quiz.isEnded()) {
//show scores//
} else {
// show question
var element = $("#question");
element.innerHTML = quiz.getQuestionIndex().text;
// show choices
var choices = quiz.getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var elementChoice = document.getElementById("choices" + i);
elementChoice.innerHTML = choices[i];
}
showProgress();
}
}
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populate();
};
}
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var elementProg = $("#progress");
elementProg.innerHTML = "Question " + currentQuestionNumber + "of " +
quiz.questions.length;
}
function showScores() {
var gameOverHtml = "<h1>Result</h1>";
gameOverHtml += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var elementQuiz = $("#quiz");
elementQuiz.innerHTML = gameOverHtml;
}
var questions = [
new Question("What famous Mathematitian developed a sequential formula
for the Golden Ratio (Phi)?", ["Issac Newton","Albert Einstein","Leonardo
Bigollo","Copernicus"], "Leonardo Bigollo"),
new Question("Who saved Apple from going bankrupt in the '90s?",
["Michael Dell", "Bill Gates", "Mark Cuban", "Warren Buffet"], "Bill
Gates"),
new Question("Though PHP may appear to look simpler than javascript,
why is js the top scrtipting language?", ["Gives instant-feedback", "It's
less vulnerable to breach", "Much more control without interferring with
bandwith", "All reasons shown!"], "All reasons shown!"),
new Question("What is the Golden Ratio?", ["1.618", "5.1", "0.618",
"0.3218"], "1.618"),
new Question("People get shocked when they see PHI is in every great
picure they see, what's an easy way to tell where phi is?", ["Look for the
embeded Greek letter, phi.", "Look at the center of the image, youll notice
that key elements are just slightly off-center.", "console.log to find it",
"take out a ruler and measure for it."], "Look for the embedded Greek
letter, phi.")
];
var quiz = new Quiz(questions);
populate();
I'm hoping to get some clarity as to why the code wont work even after following a video start to end 3x just to double check....
I have until 5pm 7/25/2019 (today) to finish this!
please help!
also i never knew you can split js into multiple files instead of killing yourself all in one...so that was cool to find out tonight...woulda saved me the past 5 days of headaches but i love this and learning how to do it!
Change document.getElementById("choices" + i) to document.getElementById("choice" + i)
choices should be choice :)
I am working on a phonegap app. I am facing some problem while passing value that I am getting from sqlite DB to jquery function.
I am passing a simple date variable to onclick = popUP("+date+");, but on the receiving end I am getting some different value. For example if date contains 2015-02-24 the popUP is receiving 1989. Here is my code:
//function will be called when process succeed
function resultSuccess(tx,response) {
for(var i=0;i<response.rows.length;i++){
date = response.rows.item(i).ARTI_DATE;
//alert("Title is : " +response.rows.item(i).ARTI_TITLE +"Date is : "+response.rows.item(i).ARTI_DATE+ "Des is : "+response.rows.item(i).ARTI_DESCRIP);
var margin = 10;
$("#routeContainer").append("<div style = 'margin-left: " + margin + "px;' class = 'test' id='d"+i+"' onclick='popUp("+date+")'><p style='padding-top: 90px;'><b>Thought for the..</b> <br/>Date: <span id='t"+i+"'>"+date+"</span> </p></div> ");
$('.test').css('background', 'url(img/thumbs/thought.jpg) no-repeat').height(100).width(100);
//$('.test').append($('<input></input>').attr('id','d'+i).attr('type','hidden').attr('value',date));
}
}
function popUp(d) {
alert("Value is " +d);
var db = window.openDatabase("DEVICEDATA", "1.0", "Device data", 200000); //will create database DEVICEDATA
db.transaction(SelectDesc, resultError, resultSuccess);
}
I do apologize if this is an easy fix, I'm a tad new to jquery. To start I don't think that it is my initial call that is messing up because if I put a simple alert function in than it will work fine onclick, basically when this <li> is clicked on, jquery trigers an ajax to php function sending the class of the <li> to a php script and back, opening an alert with the result. As far as I can tell it should be working, but again my knowledge is rather limited. Any change anyone can take a look at what I have and see if you can clean it up at all, currently nothing happens onclick, no errors even appear in the console. But I imagine that even my ajax call is wrong. Any ideas why nothing happens on click?
HTML:
<li title = "Previous Month" id = "changeMonthBack" class = "<?php echo date('n'); ?>"><img src="images/leftArrow.gif" width="54" height="45" alt="previous month"></li>
jQuery/javascript:
//javascript document
$(document).ready(function(){
//need to do an onclick for getting the new month(previous)
$(".changeMonthBack").click(function(){
function calendar(){
//set the id for php
var identifier = 1;
//get the class to use for month
var str = document.getElementById("changeMonthBack").class;
//get the month number
//if the month is 1, we obviously need it to be 12
if str == 1{
var month = 12;
}
else{
var month = str - 1;
}
$.post("redraw.php"),{
identifier: identifier,
month: month
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
};
})//end function 1
});
There are multiple problems with the script.
1. As Aesthete suggested the selector should be an id selector #changeMonthBack
2. You are creating a closure method called calendar but never called it
3. There were multiple syntax error (Use a javascript editor like spket)
You are creating a function called calendar but never calls it.
$(document).ready(function() {
// need to do an onclick for getting the new month(previous)
$("#changeMonthBack").click(function() {
// set the id for php
var identifier = 1;
// get the class to use for month
var str = parseInt($(this).attr('class'),10);
// get the month number
// if the month is 1, we obviously need it to be 12
if (str == 1) {
var month = 12;
} else {
var month = str - 1;
}
$.post("redraw.php", {
identifier : identifier,
month : month
},
function(data, status) {
alert("Data: " + data + "\nStatus: "
+ status);
});
});
});
I am trying to work through how to publish items from multiple arrays while first searching through the separate array elements and then return only those items which match a certain criteria. The following code does not do this yet.
enter code here<div id="myDiv">
<script type="text/javascript">
var $ = function(id) {
return document.getElementBuId(id);
}
var title = new Array("Barbecuing in the Rain","Picnicing in the Arctic",
"How to Saute on a Radiator", "A Real Grasshopper: Bartending with Insects",
"Food with a Bullet: Cooking in Camden", "Mirepoix for Dummies");
var price = new Array(18.50, 23.95, 41.95, 5.95, 13.00, 99.00);
var binding = new Array("Hardcover", "Paperback", "Hardcover", "Paperback", "Paperback", "Hardcover");
var pubYear = new Array(2002, 1975, 2004, 2006, 2001, 1997);
var NYTBestSeller = new Array(true, true, false, false, true, true)
var seriesTitle = new Array("Food Network", "The Food Network",
"Culinary Shortcuts", "Sunset Libations",
"Food Network", "The Food Network");
var bargainBooks = ("Food Network Hot Selling Bargain Book");
for (i in title) {
if (((price[i] <= 25 && binding[i] == "Hardcover") ||
(price[i] <= 15 && binding[i] == "Softcover")) && (pubYear[i] >= 2000) &&
(NYTBestSeller[i] == true) && (seriesTitle[i] == "Food Network") || (seriesTitle[i] == "The Food Network"))
//document.write("<span color='red'>This line is red</span>");
document.write(title[i] + "<br />");
document.write(price[i] + "<br />");
document.write(binding[i] + "<br />");
document.write(pubYear[i] + "<br />");
document.write(NYTBestSeller[i] + "<br />");
document.write(seriesTitle[i] + "<br />" + "<hr/>");
}
</script>
I am searching for books that met a certain criteria and then trying to output where that book is on the page a message of Hot Selling Book in green. But I can't figure out how to make the document.write work. document.write().style.color="green" does not work.
document.write output text only, you have to write your own tags there (a div styled as green for example).
However I suggest you a different approach, what about an empty div with an id and then do the following:
document.getElementById('your-div-id').innerHTML = 'text <br /> <span style="color: green;">other text</span> and so on';
Will also reorganize code in a better way.
Document.write will only append code to the end of the output stream (the document in this case), so you can't specify where output will appear.
Edit 1:
Also, what about using objects in this case? As far as I can see, you are using arrays to emulate their behaviour:
var myObjArray = [
{
title: 'mytitle1',
price: '10$',
binding: 'dunno',
pubYear: 'dunno-again',
NYTBestSeller: true,
seriesTitle: 'Something'
},
{
...other object data...
}
]
document.getElementById('your-div-id').innerHTML += myObjArray[0].title + '<br />' + myObjArray[0].price;
Hope you can find it interesting