Add link to this JavaScript code [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I have the following javascript code for a rotating image. Those images are in a separate folder from the javascript. I want to link the rotation itself to another page. All images will go to the same link. The current code works great but I just don't know where I add the a href code or its syntax.
// JavaScript Document
//
// Type the number of images you are rotating.
NumberOfImagesToRotate = 3;
FirstPart = '<img src="domain/rotatingimages';
LastPart = '.gif" height="250" width="388">';
function printImage() {
var r = Math.ceil(Math.random() * NumberOfImagesToRotate);
document.write(FirstPart + r + LastPart);
}

Try this format
<img src='image_src' border="0"/>
It is up to you if you want to define the target attribute in <a> tag.

// JavaScript Document
//
// Type the number of images you are rotating.
var numberOfImagesToRotate = 3;
// Edit the destination URl here
var linkUrl = 'example.html';
// HTML-partials
var imgFirstPart = '<img src="domain/rotatingimages';
var imgLastPart = '.gif" height="250" width="388" border="0">';
var anchorFirstPart = '<a href="';
var anchorSecondPart = '">';
var anchorLastPart = '</a>';
function printImage() {
var r = Math.ceil(Math.random() * numberOfImagesToRotate);
document.write(anchorFirstPart + linkUrl + anchorSecondPart + imgFirstPart + r + imgLastPart + anchorLastPart);
}

Related

Dynamically create HTML using array from local storage [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to retrieve a title, description and image from local storage that I saved from a form but I am not sure how to dynamically create HTML to display it.
function readData() {
var formData={};
formData.title = document.getElementById("title").value;
formData.desc = document.getElementById("desc").value;
formData.img= document.getElementById("img").files[0].name;
return formData;
}
function displayBlog(){
var retrievedObject =JSON.parse(localStorage.getItem("blogData"));
var blogs1 = '';
for (blogpost of blogpost1) {
blogs1 += '<div>' +
'<div class="card border-secondary mb-3">' +
'<h5 class="card-header"></p></h5>' +
'<div class="card-body">' +
'<div class="blog-post">' +
'<h2 class="blog-post-title"></h2><br>' +
'</p>' +
'</div>' +
'</div>' +
'</div>' +
'</div><br></br>'
}
document.getElementById("blogs").innerHTML = blogs1;
}
Update: ended up using
document.body.appendChild(btn);
after research
You can work with JavaScript DOM Elements, check theese functions document.creatElement() and node.appendChild().
So it would go something like this:
function displayBlog() {
var retrievedObject =JSON.parse(localStorage.getItem("blogData"));
var blogs1 = document.createElement('div'); // container div
for (blogpost of blogpost1) {
var parentDiv = document.createElement('div'); // create parent div
parentDiv.className = 'card border-secondary mb-3'; // set parent div class names
// then here you create yor child tags, for example:
var h5 = document.createElement('h5');
h5.className = 'card-header';
h5.innerHTML = blogpost.title; // set the title here from your variable
// and next you append your child tag to the parent:
parentDiv.appendChild(h5);
// then you go on building your desired structure...
// when done you append your parentDiv from this loop iteraction to your container variable
blogs1.appendChild(parentDiv);
}
// at the end you set your container HTML to this element
document.getElementById("blogs").innerHTML = blogs1.outerHTML;
}

Displaying Variables in Buttons? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm very new to JavaScript and am attempting to make a simple maths game.
I'm holding the correct answer to my randomly generated maths questions in a variable named correctAnswer. I would like the value of this variable to be displayed in a button - so that when the user clicks it, they see a "Well done!" message.
This is what I've got so far - just the code to create my random questions:
var firstNumber;
var secondNumber;
var correctAnswer;
var userAnswer;
function additionQuestion() {
firstNumber = Math.floor(Math.random() * 10) + 11
secondNumber = Math.floor(1 + Math.random() * 9);
document.getElementById("additionQuestion").innerHTML = + firstNumber + " + " + secondNumber + " = ";
correctAnswer = (firstNumber + secondNumber);
}
Would anyone be able to help me with this?
Thanks in advance.
You can display value in a button, by accessing its value property.
For example you have a button like this
<input type="button" id="correct" />
you can display value in it like this:
document.getElementById("correct").value = correctAnswer;
use this line of code to change your button display text:
document.getElementById("yourButtonID").innerHTML= correctAnswer;
check this for more info: http://www.w3schools.com/jsref/prop_html_innerhtml.asp
use jquery;
var yourVariable = 48;
$(document).ready(function(){
$('.your-button').data('answer', 48);
$('body').on('click', '.your-button', function(e){
if($(this).data('answer') === yourVariable){
alert('good answer');
}else{
alert('try again');
}
});
});

Why doesn't my local storage work? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am trying to localStore the history but it does not work. I tried JSON.stringify and a script called JStorage but I couldn't get either to work.
function updateHistory(video) {
getHistory();
blacklist[video["id"]] = true;
myhistory.push(video);
var html = "<li class=\"history\">" +
"<img class= \"img-rounded\" src=\"{0}\"/>" +
"<p><b title=\"{2}\"><a class=\"extendedLink\" href=\"javascript:watchHistoricVideo(\'{1}\');\"><span></span>{2}</a></b><br>" +
"by {3}<br>" +
"{4} | {5} views</p>" +
"</li>";
$("#myhistory").prepend(html.format(video["thumbnail"],
video["id"],
video["title"],
video["uploader"],
video["length"],
video["views"]));
saveHistory();
}
function saveHistory() {
localStorage.setItem(myhistory, myhistory.innerHTML);
}
(The alert does show up)
function getHistory() {
localStorage.getItem(myhistory);
alert("working");
}
The point is, instead of storing the html part you better store the video object instead, you can store videos based on their id, and instead of array use javascript object:
function setVideo(video) {
var videos = JSON.parse(localStorage.getItem("myhistory") || "{}");
videos[video["id"]]=video;
localStorage.setItem("myhistory", JSON.stringify(videos));
}
function getVideos() {
var myhistory = localStorage.getItem("myhistory");
if(!myhistory) return {};
else return JSON.parse(myhistory);
}
function getVideo(id) {
var myhistory = localStorage.getItem("myhistory");
if(!myhistory) return null;
var videos = JSON.parse(myhistory);
return videos[id] || null;
}
now you can use getVideo to retrieve the video object by id.you can separate the part which shows the video, like:
function showVideo(video) {
blacklist[video["id"]] = true;
var html = "<li class=\"history\">" +
"<img class= \"img-rounded\" src=\"{0}\"/>" +
"<p><b title=\"{2}\"><a class=\"extendedLink\" href=\"javascript:watchHistoricVideo(\'{1}\');\"><span></span>{2}</a></b><br>" +
"by {3}<br>" +
"{4} | {5} views</p>" +
"</li>";
$("#myhistory").prepend(html.format(video["thumbnail"],
video["id"],
video["title"],
video["uploader"],
video["length"],
video["views"]));
}
let's say you want to show the whole videos in the history:
var videos = getVideos();
for(var id in videos){
showVideo(videos[id]);
}

Convert comma separated list to Unordered List [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Looking for any PHP, Jquery, javascript solution to take data separated by commas and turn it into an unordered list.
To explain further, I have imported a CSV file into wordpress and one element block contains lots of data that is comma separated and I need it to display as a list.
All help is appreciated!
In PHP
$list = 'item1,item2,item3,item4';
$list = explode(',', $list);
shuffle($list);
$html = '<ul>';
foreach($list as $item) {
$html .= '<li>' . $item . '</li>';
}
$html .= '</ul>';
print $html;
In JavaScript
var list = 'item1,item2,item3,item4';
list = list.split(',');
list.sort(function() { return 0.5 - Math.random() });
var html = '<ul>';
for(var i=0; i<list.length; i++) {
html += '<li>' + list[i] + '</li>';
}
html += '</ul>';
There are cleaner ways to write this, but hopefully this will give you an idea of how it can be done using jQuery.
$(function(){
$csv = $("#csv")
items = $csv.text().split(",")
$csv.replaceWith($("<ul/>"))
items.forEach(function(item){
$("ul").append("<li>"+item+"</li>")
})
})
And here's the fiddle: http://jsfiddle.net/JmwDw/
HTML
<ul id="ul-test">
</ul>
JavaScript
var CSV = "a,b,c,d,e";
var arrCSV = CSV.split(','),
ul = document.getElementById("ul-test");
for (var i = 0, len = arrCSV.length; i < len; i++) {
var li = document.createElement("li");
var text = document.createTextNode(arrCSV[i]);
li.appendChild(text);
ul.appendChild(li);
}
JSFiddle

How do I make a loop advance using onclick?

I've been trying to figure this out for a while, and I'm totally stumped.
I'm writing a program that is supposed to display a basic series of multiple-choice questions. You see a question, you click one of the answers, and you move on to the next question.
The problem is, I can't figure out how to display one question, then display the next question when the user clicks one of the buttons. Nothing happens when I click a button. What's going wrong?
// progress meter
var progress = new Array();
for (var i = 0; i < questions.length; i++) progress.push("0");
var i = 0;
display(0);
// display questions
function display(i) {
var prg_string;
for (var j = 0; j < progress.length; j++) prg_string += progress[j];
document.write(
"<div id = 'background'>"
+ "<div id = 'progress'>" + progress + "</div>"
+ "<div id = 'title'>-JogNog Test v1-<br></br>" + tower + "</div>"
+ "<div id = 'question'>" + questions[i].text + "</div>"
+ "<div id = 'stats'>Level " + level + "/" + total_levels + " Question " + (i + 1) + "/" + questions.length + "</div>"
+ "</div>"
);
document.write("<button id = 'answer1' onclick = 'next(questions[i].answers[0].correct)'>" + questions[i].answers[0].text + "</button>");
if (questions[i].answers.length > 0)
document.write("<button id = 'answer2' onclick = 'next(questions[i].answers[1].correct)'>" + questions[i].answers[1].text + "</button>");
if (questions[i].answers.length > 1)
document.write("<button id = 'answer3' onclick = 'next(questions[i].answers[2].correct)'>" + questions[i].answers[2].text + "</button>");
if (questions[i].answers.length > 2)
document.write("<button id = 'answer4' onclick = 'next(questions[i].answers[3].correct)'>" + questions[i].answers[3].text + "</button>");
}
// go to next question, marking whether answer was right or wrong
function next(correct) {
if(correct) progress[i] = "T";
else progress[i] = "F";
i += 1;
display(i);
}
I haven't read through your code, (you might want to work on posting SSCCEs by focusing just on the part that handles the loop) but I get the feeling a loop is not what you want here. Loops are great if you need to automatically iterate through something. But really, you want to display only a single question at a time.
The easiest way to do this, assuming you have a means of handling each question independently, is just to keep track of which question the user is up to. Display that question. When the user submits an answer, call whatever function renders a question using the counter, plus one. Make sure to check that you haven't hit the end of the quiz so that you don't reference a question that doesn't exist.
Here's some pseudocode:
var questionNumber, questions; //assume these already have values
function printQuestion(questionNumber){ ... }
function nextQuestion(){
if(questionNumber < questions){
questionNumber++;
printQuestion(questionNumber);
}
else{
showResults();
}
}
I agree with #ngmiceli that a loop isn't what you want here. You want to display one question, and then create click event handlers that will move on to the next question when the user selects an answer to the previous question.
I went ahead and created a different setup to demonstrate. You can see a demo here:
-- jsFiddle DEMO --
But I'll walk through the process. First, I set up a basic HTML document:
<body>
<h1>-Test v1-</h1>
<h2>Simple Math</h2>
<div id="container">
<div><span id="numRight">0</span> of <span id="numQuestions">0</span></div>
<div id="question"></div>
<div id="answers"></div>
</div>
</body>
Then, I created a questions array, each element in the array being an object. Each question object contains the question itself, an array of possible answers, and an "answerIdx" property that indicates the array index of the correct answer.
questions = [
{
question: 'What is 0 / 6 ?',
options: ['0','1','2'],
answerIdx: 0
},
{
question: 'What is 2 + 2 ?',
options: ['72','4','3.5'],
answerIdx: 1
}
]
I also created some other variables that point to the HTML elements I am going to want to manipulate:
numRight = 0,
numQuestions = 0,
answerDiv = document.getElementById('answers'),
questionDiv = document.getElementById('question'),
numRightSpan = document.getElementById('numRight'),
numQuestionsSpan = document.getElementById('numQuestions');
Next, I created a 'displayQuestion' function which takes a single question object as a parameter:
function displayQuestion(q) {
// insert the question text into the appropriate HTML element
questionDiv.innerHTML = q.question;
// remove any pre-existing answer buttons
answerDiv.innerHTML = '';
// for each option in the 'options' array, create a button
// attach an 'onclick' event handler that will update
// the question counts and display the next question in the array
for(i = 0; i < q.options.length; i++) {
btn = document.createElement('button');
btn.innerHTML = q.options[i];
btn.setAttribute('id',i);
// event handler for each answer button
btn.onclick = function() {
var id = parseInt(this.getAttribute('id'),10);
numQuestionsSpan.innerHTML = ++numQuestions;
// if this is the right answer, increment numRight
if(id === q.answerIdx) {
numRightSpan.innerHTML = ++numRight;
}
// if there is another question to be asked, run the function again
// otherwise, complete the test however you see fit
if(questions.length) {
displayQuestion(questions.shift());
} else {
alert('Done! You got '+numRight+' of '+numQuestions+' right!');
}
}
answerDiv.appendChild(btn);
}
}
Finally, I displayed the first question:
displayQuestion(questions.shift());

Categories

Resources