How do I automatically create images in HTML or Javascript? - javascript

I am prepared to take hits on this question, because I don't even know how to go about researching this. I did try, don't get me wrong. Maybe someone can tell me what it would even be called. Anyways, I have an .htm file and am passing a variable to it like
Response.Redirect("multiImage.htm?val1=2");
I want to generate val1 many images. so in this example, val1=2, so 2 images generated. I'm not very skilled with html or javascript and this is what I have so far:
<!--When a new camera is added, one needs to change the bound in the for loop in the javascript function in part a.
Then add a new image in part b.-->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--********************************Part a**********************************-->
<title>Cameras</title>
<script type="text/javascript" language="JavaScript">
var num = '<%= Request.QueryString("val1") %>';
function refreshIt() {
if (!document.images) return;
for (var i = 1; i <= num; i++) {
document.getElementById("imgcontainer" + i).src = "/Imghandler2.ashx?id=" + i + "&rand=" + Math.random();
}
setTimeout('refreshIt()', 1000);
}
</script>
</head>
<!--********************************Part b**********************************-->
<body onload="setTimeout('refreshIt()',1000)">
<table>
<tr>
That part works, and so does this:
<!-- <td><img id="imgcontainer1" src="/Imghandler2.ashx?id=1" alt="cam image" /></td>
<td><img id="imgcontainer2" src="/Imghandler2.ashx?id=2" alt="cam image" /></td>
</tr>
<tr>
<td><img id="imgcontainer3" src="/Imghandler2.ashx?id=3" alt="cam image" /></td>
<td><img id="imgcontainer4" src="/Imghandler2.ashx?id=4" alt="cam image" /></td>
</tr>
<tr>
<td><img id="imgcontainer5" src="/Imghandler2.ashx?id=5" alt="cam image" /></td>
<td><img id="imgcontainer6" src="/Imghandler2.ashx?id=6" alt="cam image" /></td>-->
But I have commented the above out, because I want to auto generate that. Something like this below. And I know this doesn't work, but hopefully it will give an idea of what I'm trying to do:
<script type="text/javascript" language="JavaScript">
var num = '<%= Request.QueryString("val1") %>';
for (var i = 1; i <= num; i++) {
document.write('<tr>')
document.write('<img id="imgcontainer[i+1]" src="/Imghandler2.ashx?id=[i+1]" alt="cam image" />')
document.write('</tr>')
}
</script>
</tr>
</table>
</body>
</html>
Like I said, I don't even know how I would go about researching this. I did try, but didn't find what I needed. Is this even possible?

After more research I found out how to do this. Here is my full html code:
<!--This .htm file creates an img for the image to be displayed. The number img's created is equal to the number
of cameras selected in "Main.aspx"-->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Cameras</title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<!--*************************beginning of javascript code******************************-->
<script type="text/javascript" language="JavaScript">
// Function gets the parameter values in the url string.
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Function programmatically creates a new img for each camera selected in Main.aspx.
function add() {
for (var i = 1; i <= getParameterByName('val1'); i++) {
var element = document.createElement("img");
element.setAttribute("id", "imgcontainer" + i.toString());
element.setAttribute("src", "/Imghandler2.ashx?id=" + i.toString());
element.setAttribute("alt", "cam image");
document.getElementById("table1").appendChild(element);
}
}
// Function updates each image in each img
function refreshIt() {
if (!document.images) return;
for (var i = 1; i <= getParameterByName('val1'); i++) {
document.getElementById("imgcontainer" + i).src = "/Imghandler2.ashx?id=" + i + "&rand=" + Math.random();
}
setTimeout('refreshIt()', 1000);
}
</script>
<!--*************************end of javascript code******************************-->
</head>
<body onload="add(); setTimeout('refreshIt()',1000);">
<table id="table1">
</table>
</body>
</html>

Related

My javascript calculator doesn't work

I am trying to create a web calculator utilizing values of text input as numbers and replacing a label at the bottom with the result. Although the problem I am facing is that the functions are either not being called or some other stuff. I am just starting out on Javascript, if you guys would point the problem out, I'll be much grateful.
<!DOCTYPE html>
<html>
<head>
<title>Calc+</title>
<link rel="stylesheet" href="calculator.css">
</head>
<body>
<header>
<div class="container"><center><p><strong>Tarun's</strong>|Calculator</p>
</center></div>
</header>
<section id="calculator">
<div class="container">
<table id="inputs"><tr>
<td><input type="text" id="firstnumber"></td>
<td><input type="text" id="secondnumber"></td>
</tr>
</table>
<table id="operators" cellpadding="0" cellspacing="7">
<tr>
<td id="plus"><button onClick="addition()">+</button></td>
<td id="minus"><button onClick="difference()">-</button></td>
</tr>
<tr><td id="multiply"><button onClick="multiplication()">*</button></td>
<td id="divide"><button onClick="division()">/</button></td></tr>
<tr>
<td colspan="2"><center><label id="result">result</label></center></td>
</tr>
</table>
</div>
</section>
</body>
</html>
function additon()
{
var a = document.getElementById('firstnumber').value;
var b = document.getElementById('secondnumber').value;
document.getElementById("result") = a + b;
}
function difference()
{
var a = document.getElementById('firstnumber').value;
var b = document.getElementById('secondnumber').value;
document.getElementById("result").innerHTML = a - b;
}
function multiplication()
{
var a = document.getElementById('firstnumber').value;
var b = document.getElementById('secondnumber').value;
document.getElementById("result").innerHTML = a * b;
}
function division()
{
var a = document.getElementById('firstnumber').value;
var b = document.getElementById('secondnumber').value;
document.getElementById("result").innerHTML = a / b;
}
There are four major problems with your code.
First the whole JavaScript code (starting with "function addition()") is not inside a script tag. Currently it just gets interpreted as text, thats the reason why you should see it at the bottom when you load your side. To fix this you have to embed the code inside a script tag. The easiest way to do this is inside the head tag as follows:
<!DOCTYPE html>
<html>
<head>
<title>Calc+</title>
<link rel="stylesheet" href="calculator.css">
<script>
function additon()
//other functions here
</script>
</head>
<body>
Second the addition function does not set the innerHTML. Just set the innerHTML there like you did with the other functions.
Third, if you get the value as you try it, the type is actually a string. If you do string + string, the result is a concatination. So "1" + "1" = "11". To change this, just add a + before the a in the addition case, as follows
document.getElementById("result").innerHTML = +a + b;
(Thanks to Frederik Hansen who pointed that one out in the comments.)
Fourth, the addition function isn't named correctly. You wrote additon but you meant addition.

switch from image to random image onclick with JavaScript

I'm trying to build something that would resemble a slide show, where you have an image and when you click on it, it is replaced by another randomly in my series of images. I first tried with simple html, but of course the images don't switch randomly. So I did my research and found that it could be done with an array in Javascript. I just don't really know a lot about javascript…
This is what I could find but it doesn't work, I'm sure there is a stupid mistake in there that I can't see:
this is my javascript
function pickimg2() {
var imagenumber = 2 ;
var randomnumber = Math.random();
var rand1 = Math.round((imagenumber-1) * randomnumber) + 1;
myImages1 = new Array();
myImages1[1] = "img_01.gif";
myImages1[2] = "img_02.gif";
myImages1[3] = "img_03.gif";
myImages1[4] = "img_04.gif";
myImages1[5] = "img_05.gif";
myImages1[6] = "img_06.gif";
myImages1[7] = "img_07.gif";
myImages1[8] = "img_08.gif";
myImages1[9] = "img_09.gif";
var image = images[rand1];
document.randimg.src = "myImages1";
}
there is my html
<!DOCTYPE html>
<html>
<head>
<title>mur</title>
<link rel="stylesheet" href="style.css">
<link rel="JavaScript" href="script.js">
</head>
<body onLoad="pickimg2">
<div class="fenetre">
<img src="img_01.gif" name="randimg" border=0>
</div>
</body>
</html>
If someone has another solution I'm open to it!
Fix your script link like RamenChef mentioned:
<script type="text/javascript" src="script.js"></script>
Here's the updated code, check console.log to see the different image urls getting requested.
var myImages1 = new Array();
myImages1.push("img_01.gif");
myImages1.push("img_02.gif");
myImages1.push("img_03.gif");
myImages1.push("img_04.gif");
myImages1.push("img_05.gif");
myImages1.push("img_06.gif");
myImages1.push("img_07.gif");
myImages1.push("img_08.gif");
myImages1.push("img_09.gif");
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function pickimg2() {
document.randimg.src = myImages1[getRandomInt(0, myImages1.length - 1)];
}
<div class="fenetre">
<a href="#" onClick="pickimg2();return false;">
<img src="img_01.gif" name="randimg" border=0>
</a>
</div>
this code bellow is working. I hope it's what you were asking for
var images = [
"http://img1.science-et-vie.com/var/scienceetvie/storage/images/galerie/deepsea-challenge-le-film-de-james-cameron-livre-des-images-inedites-des-grands-fonds-marins-5165/19818-1-fre-FR/Deepsea-challenge-le-film-de-James-Cameron-livre-des-images-inedites-des-grands-fonds-marins_square500x500.jpg",
"http://static.mensup.fr/photos/145240/carre-premieres-images-officielles-pour-assassin-s-creed-rogue.jpg",
"http://www.pnas.org/site/misc/images/16-01910.500.jpg" ];
init();
function random_image(images) {
var random = randomize(images);
while(images[random] === document.getElementById("image").src){
random = randomize(images)
}
document.getElementById("image").src = images[random].toString();
}
function randomize(array){
return Math.floor((Math.random() * (array.length)));
}
function init() {
document.getElementById("image").addEventListener("click", function(){
random_image(images);
});
random_image(images);
}
<!DOCTYPE html>
<html>
<head>
<title>Bonjour</title>
</head>
<body >
<div class="fenetre">
<img id="image" src="" name="randimg" >
</div>
</body>
</html>

how to extract substring before a specified character (comma)

I am trying to extract everything before the ',' comma. and replace it with a same name image. How do i do this in javascript or jquery? I tried this but not working for the first and the last string
here is my codes:
<html>
<head>
<script>
function splitString(stringToSplit, separator) {
var arrayOfStrings = stringToSplit.split(separator);
document.write('<img src="/images/'+ arrayOfStrings.join('.png" /><img src="/images/') + '/>');
}
</script>
</head>
<body>
<div class="slidepop">
<script> splitString(',brickfast,travel insurance,guide,sim cart,tour',',')</script>
</div>
</body>
</html>
you need to apply loop as :
for(var i = 0; i < arrayOfStrings.length; i++){
if(arrayOfStrings[i] !== ''){
document.write('<img src="/images/'+ arrayOfStrings[i].join('.png" /><img src="/images/') + '/>');
}
}
Same basic premise as #Hemanshi karelia, but instead of using document.write, I suggest creating a string from the image elements and then when all elements have been added to this image string - adding it to the div using jquery's .html(). This is advantageous because it only manipulates the DOM at the end, when all of the image elements have been built and passed into the image string that is then passed into the div, rather than all the other posted answers which alter the DOM on each iteration.
splitString('brickfast,travel insurance,guide,sim cart,tour');
function splitString(stringTotal) {
var stringPortions = stringTotal.split(",");
var imageString="";
for(i = 0; i < stringPortions.length; i++){
imageString += "<img src='/images/" + stringPortions[i] +".png'/>";
}
$('.slidepop').html(imageString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slidepop"></div>
When you use a split method you get an array of strings in return. But you are directly joining the array with the html tags. You can try something like below in which I am joining the string at a particular index of the array of strings.
<html>
<head>
<script>
function splitString(stringToSplit, separator) {
var arrayOfStrings = stringToSplit.split(separator);
document.write('<img src="/images/'+ arrayOfStrings[1].join('.png" /><img src="/images/') + '/>');
}
</script>
</head>
<body>
<div class="slidepop">
<script> splitString(',brickfast,travel insurance,guide,sim cart,tour',',')</script>
</div>
</body>
</html>`
If you want to display all images in the array of strings, you can traverse through all array like this.
<html>
<head>
<script>
function splitString(stringToSplit, separator) {
var arrayOfStrings = stringToSplit.split(separator);
var imagesHtml = '';
for(var i = 0; i < arrayOfStrings.length; i++){
if(arrayOfStrings[i] !== ''){
imagesHtml = imagesHtml + '<img src="/images/' + arrayOfStrings[i] + '.png" />'
}
}
var newDiv = $("<div></div>");
newDiv.append(imagesHtml);
$(".slidepop").append(newDiv);
}
</script>
</head>
<body>
<div class="slidepop">
<script> splitString(',brickfast,travel insurance,guide,sim cart,tour',',')</script>
</div>
</body>
</html>`

Check if shown (randomised) image is the same as last (randomised) image (jQuery & JavaScript )

(Before anything, you should know that my JS skills are very basic)
I'm trying to make my own "rapid sorting" from the game "BrainWars" on smartphones.
Basically what it should do is:
Step 1: randomise one of the 3 pictures available and show the image.
Step 2: if this image is the same as the last one ( do something )
Step 3: If this image is NOT the same as the last one ( do something else )
For now , I have a folder named "images" with 3 png's inside it.
So far I have this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Demo</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
var random_images_array = ['1.png', '2.png', '3.png'];
var lastImage = "";
function getRandomImage(imgAr, path) {
path = path || 'images/'; // Default path hier opgeven
var num = Math.floor(Math.random() * imgAr.length);
var img = imgAr[num];
var imgStr = '<img src="' + path + img + '" alt = "">';
document.write(imgStr);
document.close();
}
$(function() {
$('#btn').click(function() {
getRandomImage(random_images_array, 'images/');
setTimeout(function() {
getRandomImage(random_images_array, 'images/');
}, 2000);
});
});
</script>
</head>
<body>
<button id="btn">GO</button>
</body>
</html>
How can one achieve this ?
What about creating a lastImage variable...
var random_images_array = ['1.png', '2.png', '3.png'];
var lastImage="";
Then:
var img = imgAr[num];
if (img==lastImage) {do something}
else {lastImage=img; ... document.write(imgStr);}

Javascript/AJAX Error 404 Not found or Undefined

I have a page which loops down the first column and copies the value to a text box, and then it is supposed to query data.asp, but I keep getting an error of either
GET http://192.168.1.12/pb_search/v2/demo/data.asp?h_prodref=undefined 404 (Not Found)
or
XHR finished loading: GET "http://192.168.1.12/pb_search/v2/demo/data.asp?h_prodref=undefined". Errors from Google Chrome Developer Tools.
Both my scripts work independently, but when I piece them together, I get these erorors. I am probably missing something really simple, but I very much learning this on the fly, so any help would be appreciated.
Full Code
<%#LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<table width="50%" border="0" cellspacing="2" cellpadding="2">
<tr>
<td width="16%" class="prodref">84PS01</td>
<td width="51%"><input type="text" class="h_prodref" /><button type="button" onclick="loadDoc()">Change Content</button></td>
<td width="33%" id="demo"> </td>
</tr>
<tr>
<td class="prodref">92K002</td>
<td><input type="text" class="h_prodref" /><button type="button" onclick="loadDoc()">Change Content</button></td>
<td id="demo"> </td>
</tr>
<tr>
<td class="prodref">68F017</td>
<td><input type="text" class="h_prodref" /><button type="button" onclick="loadDoc()">Change Content</button></td>
<td id="demo"> </td>
</tr>
</table>
<script>
var prodref = document.getElementsByClassName("prodref");
var h_prodref = document.getElementsByClassName("h_prodref");
var i = 0;
for (i; i < prodref.length; i++) {
h_prodref[i].value = prodref[i].innerHTML;
function loadDoc() {
var x = document.getElementsByClassName("h_prodref");
x[i] = document.getElementsByClassName("h_prodref").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", "data.asp?h_prodref="+x[i].value, true);
xhttp.send();
}
}
</script>
So What's the Problem?
The value undefined is getting added into AJAX call that is made instead of the expected value of x[i].value. I'm making an assumption here though and that is that
http://192.168.1.12/pb_search/v2/demo/data.asp
exists and the HTTP 404 Not Found is being forced by the data.asp script as a scripted response and not because the server can't find the data.asp page.
Restructuring the JavaScript
When calling a function you don't need the entire definition at the point where you want to call it, if this was the case you would have the same function being duplicated throughout the code where it is called breaking fundamental principles in programming like DRY.
Here is a quick example of restructuring the JavaScript code:
var prodref = document.getElementsByClassName("prodref");
var h_prodref = document.getElementsByClassName("h_prodref");
var i = 0;
for (i; i < prodref.length; i++) {
h_prodref[i].value = prodref[i].innerHTML;
// Call function inside the loop
loadDoc();
}
// Definition should be defined once
function loadDoc() {
var x = document.getElementsByClassName("h_prodref");
x[i] = document.getElementsByClassName("h_prodref").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", "data.asp?h_prodref="+x[i].value, true);
xhttp.send();
}

Categories

Resources