I'm trying to make my page so a user can type a number value between 1 and 200 to get to whichever image they want to view. I've played around with the code, but I can't seem to get anything to work. Below is my code that I've tried to do this with. What am I doing wrong?
Edit: New Code:
`
<html>
<head>
<title></title>
</head>
<body style="background-color: teal;">
<form>
<center>
<div width="50%" style="width: 50%;">
<div id="main" align="middle">
<img src="page1.jpg" alt="" id="mainImg" height="90%">
</div>
<div id="imglist">
<a href="javascript:previousImage('mainImg')"><img src="previous.png" alt=""
align="left"></a>
<input id="myid" name="myid" size="3" type="text"></input>
<img src="next.png" alt="" align="right">
<script>
var imgArray = new Array();
var imgs = [];
for (var i = 0; i < 200; i++) {
imgs[i] = new Image();
imgs[i].src = "page" + (i + 1) + ".jpg";
}
function nextImage(element)
{
var img = document.getElementById(element);
for(var i = 0; i < imgArray.length;i++)
{
if(imgArray[i].src == img.src) // << check this
{
if(i === imgArray.length){
document.getElementById(element).src = imgArray[0].src;
break;
}
document.getElementById(element).src = imgArray[i+1].src;
break;
}
}
}
function previousImage(element)
{
var img = document.getElementById(element);
for(var i = 0; i < imgArray.length;i++)
{
if(imgArray[i].src == img.src)
{
if(i === 0){
document.getElementById(element).src = imgArray[imgArray.length-1].src;
break;
}
else{
document.getElementById(element).src = imgArray[i-1].src;
break;
}
}
}
}
window.onload = function() {
var elm = document.getElementById("myid"),
var img = document.getElementById("mainImg");
elm.onkeyup = function(event) {
if (this.value) {
var num = parseInt(this.value, 10);
if (num >= 1 && num <= 200 {
img.src = "page" + num + ".jpg";
}
}
}
}
</script>
</div>
</div>
</center>
</form>
</body>
</html>
Perhaps you mean for this:
if (this.value.length === 1,2,3) {
to be this:
if (this.value.length <= 3) {
In addition, I think you want to be converting the whole input value to a number, not using the individual keycodes.
I might suggest this different/simpler way of doing this that is much more DRY (don't repeat yourself):
// preload images
var imgs = [];
for (var i = 0; i < 200; i++) {
imgs[i] = new Image();
imgs[i].src = "page" + (i + 1) + ".jpg";
}
window.onload = function() {
var elm = document.getElementById("myid");
var img = document.getElementById("mainImg");
elm.onkeyup = function(event) {
if (this.value) {
var num = parseInt(this.value, 10);
if (num >= 1 && num <= 200) {
img.src = "page" + num + ".jpg";
}
}
}
}
Working Demo: http://jsfiddle.net/jfriend00/4dqbP/
Summary of changes:
Preload images in a loop rather than copied code
Construct image names dynamically
Make img variable to a local variable rather than an implicit global with var in front of it
Check to see if the input field is empty
Use parseInt() to parse the value of the input field into a number
Range check the parsed number
If in valid range, then construct the image name using that number
Related
<!--my images appear here but they are not clickable-->
<div class="image-container">
<span id="result" align="center"></span>
</div>
I need to add separate links to the images I've tried all kinds see my code, I want to add a link to the image links,
<script>
var dd = 5;
var cnt = 0;
function chng() {
var rotator = document.getElementById('stars');
var imageDir = 'images/';
// see the images below I need links adding so they can be clicked
var images = ['1.png', '2.png', '3.png', '4.png'];
cnt++;
var len = images.length;
if (cnt < dd) {
stars.src = imageDir + images[cnt];
}
else if (cnt == len) {
stars.src = imageDir + images[0];
cnt = 0;
}
}
</script>
I'm trying to use JavaScript to list images 01-40 in order automatically.
Like this:
<img src="01.jpg" />
<img src="02.jpg" />
<img src="03.jpg" />
<img src="04.jpg" />
<img src="05.jpg" />
...
I don't want to write each img src manually, as I want to use this on multiple pages
I'd like the image starting and ending number to be variables that I can edit easily.
You need the parent element for imgs:
for ( var i = FIRST_NUMBER ; i < LAST_NUMBER ; i++ ) {
var elem = document.createElement("img");
if ( i < 10 ) {
elem.setAttribute("src", "0"+i+".jpg");
} else {
elem.setAttribute("src", i+".jpg");
}
document.getElementById(PARENT_ID).appendChild(elem);
}
function img_create(startIndex, endIndex) {
for (i = startIndex; i <= endIndex; i++) {
var oImg=document.createElement("img");
oImg.setAttribute('src', i+".jpg");
//other attributes you need
document.body.appendChild(oImg);
}
}
Working example: http://jsfiddle.net/Lw3bjcx4/1/
function createImages(count, elementId) {
// Get the container element where you want to create the images
var element = document.getElementById(elementId)
// Loop count times over to create count image elements
for (var i = 0 ; i < count ; i++) {
// Create a new image element
var imageElement = document.createElement('img')
// Set the source to index.jpg where index is 0,1,2,3.... count
imageElement.setAttribute('src', i + ".jpg")
// Append the new image element to the choosen container.
element.appendChild(imageElement)
}
}
// Test to create 10 images.
createImages(10,"imgs")
You can use like this:
var imgdiv = document.getElementById('imgdiv');
var img = imgdiv.getElementsByTagName('img');
for(var i=0;i<40;i++){
img[i].src=i+'.jpg';
}
Here is an alternative to all other answers, where you don't need to use an id to put images in. Just paste the script tag where you need to have the images. For example, if you put it in a div, the script will automatically insert the images in place.
<script type="text/javascript">
var thisScriptNode = document.currentScript;
for(var i = 1 ; i <= 40 ; i++) {
var img = document.createElement("img");
img.src = ("00" + i).substr(-2) + ".jpg";
thisScriptNode.parentNode.insertBefore(img, thisScriptNode);
}
</script>
You can easily change the number of leading zeros. For example, to get numbers with three characters, replace "00" with "000" and -2 with -3.
var to = 10;
var from = 0;
for (i = from; i < to; i++){
var elem = new Element('img', { src: i + '.jpg' });
document.body.appendChild(elem);
}
it will append to <body> images with names from 0.jpg to 9.jpg
I'm looking for a way to replace an image that could be used anywhere on a page.
So if we have an example html page like this:
<html>
<head>
</head>
<body>
<img id="1" src="example.com/img/1889.png">
<div style="background: url('example.com/img/1889.png')">
<div>
<a>
<img id="2" src="example.com/img/1889.png">
</a>
</body>
</html>
Where ever - example.com/img/1889.png - appears, it must be replaced with something else.
EDIT
Unfortunately I can't use any javascript libraries. Its for a browser plugin. Nor can I use browser specific APIs
There might be some syntax errors here, but basically just try something like:
<script>
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
if (imgs[i].src == "oldImg")
imgs[i].src = "newImg";
}
}
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
if (divs[i].style.backgroundImage == "oldImg")
divs[i].style.backgroundImage = "newImg";
}
}
</script>
The following code does what you're looking for:
var images = document.querySelectorAll('[src]'), // all image and input elements
styled = document.querySelectorAll('[style]'), // all elements with inline style
iLen = images.length,
sLen = styled.length,
url = 'example.com/img/1889.png', // the string you're searching for
str = 'some/string', // replace with whatever you choose
i;
// check for 'example.com/img/1889.png' in image source
for (i = 0; i < iLen; i += 1) {
if (images[i].src.indexOf(url) !== -1) {
images[i].src = str;
}
}
// check for 'example.com/img/1889.png' in either background or background-image
for (i = 0; i < sLen; i += 1) {
if (styled[i].style.backgroundImage.indexOf(url) !== -1) {
styled[i].style.backgroundImage = 'url(' + str + ')';
}
}
Demo
I'm fairly new to JavaScript and trying to build a simple photoviewer, slideshow application. I probably have errors/wrong practices in code that I don't know about yet. The event on slideshow button fires and I can see the output in the console, however the event on the random slide show button does not fire.
HTML5 snippet
<form>
<div id="controls">
<input type="button" id="slideshow" value="Slide Show" />
<input type="button" id="randomSlideshow" value="Random Slide Show" />
</div>
</form>
<script src="js/PhotoViewer.js"></script>
</body>
JS snippet
var photosArrayGlobal = new Array();
var photoIndexGlobal = 0;
var displayGlobal;
window.onload = main;
function main() {
"use strict";
document.getElementById("slideshow").onclick = getArrayPhotosNames;
document.getElementById("randomSlideshow").onclick = randomize(photosArrayGlobal);
displayGlobal = document.getElementById("myImage");
document.getElementById("nextSlide").onclick = function () {
displayGlobal.setAttribute("src", photosArrayGlobal[1]); //Test value, image 2
};
}
function getArrayPhotosNames() {
var folderName = document.getElementById("photoFolder").value;
var commonName = document.getElementById("commonName").value;
var startNum = document.getElementById("startNum").value;
var endNum = document.getElementById("endNum").value;
var j = 0;
if (startNum > endNum) {
alert("Invalid Numbers");
}
var nameArray = new Array();
for (var i = startNum; i <= endNum; i++) {
nameArray[j] = folderName + commonName + i + ".jpg";
j++;
}
photosArrayGlobal = nameArray.slice();
console.log(photosArrayGlobal);
return nameArray;
}
function randomize(dataArray) {
var i = dataArray.length;
var j, tempi, tempj;
if (i === 0) {
return false;
}
while (--i) {
j = Math.floor(Math.random() * (i + 1));
tempi = dataArray[i];
tempj = dataArray[j];
dataArray[i] = tempj;
dataArray[j] = tempi;
}
console.log(dataArray);
}
The onclick handler is expecting a function, but you're passing it the value returned from the randomize() function (which happens to be undefined). Change it to the following:
document.getElementById("randomSlideshow").onclick = function() {
randomize(photosArrayGlobal);
};
I used the below code to upload multiple files. Its working absolutely fine but as i need to check that the file which i am uploading is duplicate or not, i am facing one problem in that. I created one function called checkDuplicate for that and calling it inside the function. But the problem is that the for loop is looping double the size of the array. I don't know why it is so. Please kindly help me if anyone has any idea.
Here is the Javascript
<script type="text/javascript">
function MultiSelector(list_target, max) {
this.list_target = list_target;
this.count = 0;
this.id = 0;
if (max) {
this.max = max;
} else {
this.max = -1;
};
this.addElement = function(element) {
if (element.tagName == 'INPUT' && element.type == 'file') {
element.name = 'file_' + this.id++;
element.multi_selector = this;
element.onchange = function() {
var new_element = document.createElement('input');
new_element.type = 'file';
this.parentNode.insertBefore(new_element, this);
this.multi_selector.addElement(new_element);
this.multi_selector.addListRow(this);
this.style.position = 'absolute';
this.style.left = '-1000px';
};
if (this.max != -1 && this.count >= this.max) {
element.disabled = true;
}
;
this.count++;
this.current_element = element;
}
else {
alert('Error: not a file input element');
}
;
};
this.addListRow = function(element) {
var new_row = document.createElement('div');
var new_row_button = document.createElement('img');
new_row_button.setAttribute("src","<%=request.getContextPath()%>/images/deletei.gif");
new_row_button.onclick = function() {
this.parentNode.element.parentNode.removeChild(this.parentNode.element);
this.parentNode.parentNode.removeChild(this.parentNode);
this.parentNode.element.multi_selector.count--;
this.parentNode.element.multi_selector.current_element.disabled = false;
return false;
};
if(checkDuplicate(element)) {
new_row.element = element;
new_row.innerHTML = element.value + " ";
new_row.appendChild(new_row_button);
this.list_target.appendChild(new_row);
}
};
};
function checkDuplicate(element) {
var arr = new Array();
var i = 0,dup=0;
//alert(new_row.element = element.value);
if(dup==0) {
arr[i++] = element.value;
dup=1;
}
alert("Length ==> "+ arr.length);
for ( var j = 0; j < arr.length; j++) {
alert("Name ==> " + arr[j]);
if(arr[j] == element.value && j>=1) {
alert("Duplicate");
} else {
alert("Not Duplicate");
arr[i++] = element.value;
}
}
}
</script>
Here is the HTML
<body>
<!-- This is the form -->
<form enctype="multipart/form-data" action=""method="post">
<input id="my_file_element" type="file" name="file_1">
<input type="submit">
<br/>
<br/>
Files:
<!-- This is where the output will appear -->
<div id="files_list"></div>
</form>
<script>
var multi_selector = new MultiSelector(document
.getElementById('files_list'), 15);
multi_selector.addElement(document.getElementById('my_file_element'));
</script>
</body>
</html>
because you have the arr[i++] = element.value; in the last line, and j < arr.length in the for, so every time the array.lenght gets bigger and bigger.
change the for line to these two lines:
var len = arr.length;
for ( var j = 0; j < len; j++) {