Detect img src and then change it with javascript - javascript

This is my code:
var i;
var pic = document.getElementById('image');
var picSrc = pic.src;
var fullSrc = picSrc.split('h.jpg')[0] + '.jpg';
pic.src = fullSrc;
document.getElementById('next').onmousedown = function () {
i = 0;
// it works up to here
pic.addEventListener("DOMAttrModified", function(event) {
if (i == 0 && event.attrName == "src") {
pic = document.getElementById('image');
i = 1; // this is to prevent endless loop
picSrc = pic.src;
fullSrc = picSrc.split('h.jpg')[0] + '.jpg';
pic.src = fullSrc;
}
});
return true;
};
It should work on imgur's horizontal layout albums, and replace the low-res images with full-res ones, one image at a time (currently displayed image).
On click of the "next" button, a new image is displayed. However, the script does not load the next full-res image. It only works with the first image loaded.

You're messing up your scope completely, invalidating the entire code after the first run. This should also pop up more than enough errors in your console. Reshuffle assignments to the right spot:
document.getElementById('next').onmousedown = function () {
var i;
var pic = document.getElementById('image');
var picSrc = pic.src;
var fullSrc = picSrc.split('h.jpg')[0] + '.jpg';
pic.src = fullSrc;
pic.addEventListener("DOMAttrModified", function(event) {
if (i == 0 && event.attrName == "src") {
pic = document.getElementById('image');
i = 1; // this is to prevent endless loop
picSrc = pic.src;
fullSrc = picSrc.split('h.jpg')[0] + '.jpg';
pic.src = fullSrc;
}
});
return true;
};
Depending on how the page works specifically (I can't see without having a real world use case) you might have to reassign the entire mousedown event as well.

On every mousedown you are adding a new DOMAttrModified event listener.
Try arranging your code to something like following:
var pic = document.getElementById('image');
var i;
pic.addEventListener("DOMAttrModified", function(event) {
if (i == 0 && event.attrName == "src") {
//pic = document.getElementById('image');
i = 1; // this is to prevent endless loop
picSrc = pic.src;
fullSrc = picSrc.split('h.jpg')[0] + '.jpg';
pic.src = fullSrc;
i = 0;
});
document.getElementById('next').onmousedown = function () {
var picSrc = pic.src;
var fullSrc = picSrc.split('h.jpg')[0] + '.jpg';
pic.src = fullSrc;
});
You should also try using the addEventListener instead of onmousedown

Related

use for-loop in javascript to assign different sources for audiofiles

I'm trying to build a soundboard (similar to therapboard dot com) - and i want javascript to create the images (named niels1.png, niels2.png...) alongside the fitting sound (1.ogg, 2.ogg,...) when the image is clicked, via a loop.
The image part works, there's also a sound being played when i click on any of the images, but it's the same sound (in this case the last from the loop... so 3.ogg). Is what i want doable with the fairly easy start i've come up with so far?
<script>
var i;
for(i=0; i<4; i++){
var imgsrc = "niels" + i + ".png";
var audiosrc = i + ".ogg";
var image = document.createElement("IMG");
image.setAttribute("src", imgsrc);
image.addEventListener('click', myPlay);
var audio = document.createElement('audio');
audio.src = audiosrc;
function myPlay(){
var audio = new Audio (audiosrc);
audio.play();
}
document.body.appendChild(image);
}
</script>
Try this. You have a closure issue and this removes the need for a closure
document.body.addEventListener('click', function(e) {
var tgt = e.target;
if (tgt.tagName === "IMG") {
var audiosrc = tgt.getAttribute("data-audio");
if (audiosrc) {
var audio = new Audio(audiosrc);
audio.play();
}
}
})
for (var i = 0; i < 4; i++) {
var imgsrc = "niels" + i + ".png";
var audiosrc = i + ".ogg";
var image = document.createElement("IMG");
image.setAttribute("data-audio", audiosrc)
image.setAttribute("src", imgsrc);
document.body.appendChild(image);
}

Propagation of Script

I probably should not be attempting this, but I have gotten so far and I don't want to give up now. I want to create my own Lightbox type script. I can create an absolute div with the class ligthbox and it covers the page. Then I create a img that is fixed and it animates when loading. The I also have nav arrows to move through the photos. All works accept when I click on the arrows it creates new close X and arrows. I don't understand because the is done through the animation function which is not attached to the arrow function.
I have added event.stopPropagation(); to the arrow function and the animate function but that did not work.
The function that initiates everything.
jQuery(".marks-lightbox img").click( function() {
var Img = jQuery(this),
cImg = Img.attr("src"),
allImg = jQuery(".marks-lightbox img");
//finding the current img from the available images
for(i=0; i < allImg.length; i++) {
if( jQuery(allImg[i]).attr("src") == Img.attr("src") ) {
lbImgCurrent = i;
}
}
makeLightBox()
});
function makeLightBox() {
var bodyHeight = jQuery("body").height(),
lightbox = jQuery("<div>").addClass("lightbox").css({"width":"100vw","height":bodyHeight}),
scrollTop = 72,
lbContainer = jQuery("<div>").addClass("lbContainer"),
lbImg = jQuery(".marks-lightbox img"),
imgSRC = jQuery(lbImg[lbImgCurrent]).attr("src"),
lbClose = jQuery("<span>").addClass("lb-close").text("X");
jQuery("body").prepend(lightbox);
lbContainer.appendTo(".lightbox");
jQuery('<img src="'+ imgSRC +'">').load(function() {
jQuery(this).appendTo(".lbContainer").css("display","none").addClass("lb-image");
var w = jQuery(".lb-image").width(),
h = jQuery(".lb-image").height(),
lbw = lightbox.width(),
margin = (lbw - w) /2;
jQuery(this).appendTo(".lightbox").css({"position":"fixed","display":"block","width":0,"height": 0}).animate({"top":scrollTop,"width":w,"height":h,"margin-left":margin, "margin-right":margin},1000,function(event){
var lbimg = jQuery(this),
lbH = lbimg.height() + 63,
lbLeft = lbimg.offset().left,
lbW = lbimg.width(),
larrow = jQuery("<div><</div>").addClass("left-arrow-lb lb-arrow"),
rarrow = jQuery("<div>></div>").addClass("right-arrow-lb lb-arrow");
larrow.appendTo("body").css({"position":"fixed","top":lbH/2,"left":lbLeft+18});
rarrow.appendTo("body").css({"position":"fixed","top":lbH/2,"left":lbLeft+lbW-90});;
lbClose.appendTo(".lightbox").css({"position":"fixed","top": lbH,"left": lbLeft+lbW - 18});
});
});
}
Here is the click function
jQuery("body").on("click",".left-arrow-lb", function() {
console.log(jQuery(this));
var lbImgLength = jQuery(".marks-lightbox img").length,
lbImg = jQuery(".marks-lightbox img");
lbImgCurrent = (lbImgCurrent < 1 ) ? lbImgLength : lbImgCurrent -1;
var imgSRC = jQuery(lbImg[lbImgCurrent]).attr("src");
console.log(imgSRC);
jQuery(".lb-image").attr("src",imgSRC);
});
Every click creates a load new img scr and animates the photo (unexpectedly) and creates new arrows and close x.
I found it was the on("load"... working every time an image was being loaded. So I created a var reload and set it to true. The in the on(load... function I said if not true return false. In the arrow functions set the reload to false. This prevented the on(load... working reloading.

Select thumbnails with PDFjs

After upload a pdf i show with PDF.js a thumbnails and work it.
$(document).ready(function () {
if (!PDFJS.workerSrc && typeof document !== 'undefined') {
// workerSrc is not set -- using last script url to define default location
PDFJS.workerSrc = (function () {
'use strict';
var scriptTagContainer = document.body ||
document.getElementsByTagName('head')[0];
var pdfjsSrc = scriptTagContainer.lastChild.src;
return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js');
})();
PDFJS.workerSrc = 'pdfjs-dist-master/build/pdf.worker.js';
}
$("#pdfInp").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
showInCanvas(e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
});
function convertDataURIToBinary(dataURI) {
var BASE64_MARKER = ';base64,';
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for (i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
function showInCanvas(url) {
// See README for overview
'use strict';
// Fetch the PDF document from the URL using promises
var pdfAsArray = convertDataURIToBinary(url);
PDFJS.getDocument(pdfAsArray).then(function (pdf) {
// Using promise to fetch the page
// Get div#container and cache it for later use
var container = document.getElementById("container");
// Loop from 1 to total_number_of_pages in PDF document
for (var i = 1; i <= pdf.numPages; i++) {
// Get desired page
pdf.getPage(i).then(function(page) {
var scale = .3;
var viewport = page.getViewport(scale);
var div = document.createElement("div");
// Set id attribute with page-#{pdf_page_number} format
div.setAttribute("id", "page-" + (page.pageIndex + 1));
// This will keep positions of child elements as per our needs
//div.setAttribute("style", "position: relative");
div.setAttribute("class", "page");
// Append div within div#container
container.appendChild(div);
// Create a new Canvas element
var canvas = document.createElement("canvas");
// Append Canvas within div#page-#{pdf_page_number}
div.appendChild(canvas);
var node = document.createElement("p");
var textnode = document.createTextNode("pagina " + (page.pageIndex + 1));
node.appendChild(textnode);
div.appendChild(node);
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
// Render PDF page
page.render(renderContext);
});
}//END LOOP
});
}
});
But i want select a multiple thumbnail show it. I think possible with the class css. This the code
$.fn.seleziona = function() {
var menuSel = $(this);
menuSel.find('.page').on('click', function() {
if ($(this).hasClass('open')) {
$(this).removeClass('open');
} else {
$(this).addClass('open');
}
});
};
$(document).ready(function(){
$("#container").seleziona();
});
end not work. That code worked only the DOM be present before the upload

How to retrieve data from a local var

i have this script in my html code
<script typre="text/javascript">
var img = new Array();
img[0] = new Image();
img[0].src = "../images/poggiatesta2.jpg";
img[1] = new Image();
img[1].src = "../images/poggiatesta1.JPG";
for (var i = 0; i < img.length; i++) {
var imagetag = document.createElement("img");
var onclick = document.createAttribute("onclick");
onclick.value = "myfun("+i+")";
var sorc = document.createAttribute("src");
sorc.value = img[i].src;
var id = document.createAttribute("id");
id.value = "my_image" + i;
var clas = document.createAttribute("class");
clas.value = "my_image_clas";
imagetag.setAttributeNode(clas);
imagetag.setAttributeNode(onclick);
imagetag.setAttributeNode(sorc);
imagetag.setAttributeNode(id);
document.body.appendChild(imagetag);
};
function myfun(i) {
var src1 = document.getElementById('my_image' + i).src;
alert(src1);
}
</script>
It allows me to store the src of a selected image in a var. Now im trying to do a check, which means an alert message that pops out if i didnt select any images like this:
function controllo() {
if ((src1 == "") || (src1 == "undefined")) {
alert("Select an image.");
}
else {
location.href = "schienale.html";
}
}
Here's the problem, src1 is a local var, how can i retrieve its data in order to complete my check funcion?
You could store src1 as a global (it is better to use a namespace, but for the sake of this question a global will do)
<script typre="text/javascript">
var src1; //Notice i've declared the variable here.
var img = new Array();
img[0] = new Image();
img[0].src = "../images/poggiatesta2.jpg";
...
Then in myFunc do:
function myfun(i) {
src1 = document.getElementById('my_image' + i).src;
alert(src1);
}
This will make src1 available everywhere.
Or, if possible, pass src1 into your controllo function.
This is the preferred method because it prevents cluttering the global namespace, but will require the code to be changed elsewhere.
This might help give you a hint though:
controllo(src1)
function controllo(src1) {
if ((src1 == "") || (src1 == "undefined")) {
alert("Select an image.");
}
else {
location.href = "schienale.html";
}
}

how to assign images using javascript to div

function ft1(){
var imgSrcs = ['1.gif','2.gif','3.gif','4.gif','5.gif','6.gif','7.gif','8.gif'];
var myImages = [], img;
for (var i = 1; i <=8; i++) {
img = new Image();
img.onload = function() {
var div0 = document.getElementById(i);
div0.style.backgroundImage = "url(" + this.src + ")";
};
img.src = imgSrcs[i];
myImages[i] = img;
}
}
<input name="Button1" type="button" value="button" onclick="ft1();" />
my div ids are 1 to 8. i want to add images for that dives using javascript.but this code didn't work properly. if u know where is the error plz tel me.
I made some changes in your code:
function ft1() {
var imgSrcs = ['1.gif', '2.gif', '3.gif', '4.gif', '5.gif', '6.gif', '7.gif', '8.gif'];
var myImages = [];
for (var i = 1; i <= imgSrcs.length; i++) {
var img = new Image();
img.src = imgSrcs[i];
var div0 = document.getElementById(i);
//I am not sure what you are trying to do in the below line.
//div0.style.backgroundImage = "url(" + this.src + ")";
div0.appendChild(img);
myImages[i] = img;
}
}
AFAIK, img.onload will not work because img variable is not part of DOM. First you need to make it part of DOM using appendChild method as shown above.
I have one question, what does this.src referring to?
try using this code in the loop
var elem = document.createElement("img");
elem.src = this.src;
elem.setAttribute("height", "250");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "alt text");
document.getElementById("placehere").appendChild(elem);
good luck!
I think You should use imgSrcs[i] instead of this.src
<script type="text/javascript">
var myImages = new Array("usa.gif","canada.gif","jamaica.gif","mexico.gif");// list of images
function changeImg(that) // function call on_click of image below
{
var newImgNumber = Math.round(Math.random()*3); // create math to random the images
while (that.src.indexOf(myImages[newImgNumber]) != -1) // make sure that the randomization corresponds to the list of images
{
newImgNumber = Math.round(Math.random()*3) // sets the math to the new image
}
that.src = myImages[newImgNumber]; // change the image
return false; // makes it able to be done again
}
</script>
If you are trying to add images to all the divs, I would try simplifying it to:
function ft1(){
var imgSrcs = ['1.gif','2.gif','3.gif','4.gif','5.gif','6.gif','7.gif','8.gif'];
for (i = 1; i <=8; i++) {
var div = document.getElementById(i);
div.style.backgroundImage = "url(" + imgSrcs[i] + ")";//make sure images are in the right folder
}
}
<input name="Button1" type="button" value="button" onclick="ft1()" /> //remove semicolon
Here is a link to a jsfiddle with color instead of images http://jsfiddle.net/CKFrantz/gLfXA/
The problem with the loop is probably that the loop-counter will be the same in all of the callbacks. (Mind that the closures just share the same scope, so the value will be 8 for all of them after the loop is exited.)
This can be overcome by a factory function (passing a simple value as argument will result in it being copied):
function loadImageToElement(id, imgscr) {
var img = new Image();
img.onload = function() {
var el = document.getElementById(id);
el.style.backgroundImage = "url(" + this.src + ")";
// we could use just the same:
// el.style.backgroundImage = "url(" + imgscr + ")";
};
img.src = imgscr;
return img;
}
function ft1(){
var imgSrcs = ['1.gif','2.gif','3.gif','4.gif','5.gif','6.gif','7.gif','8.gif'];
var myImages = [];
for (var i = 0; i < 8; i++) {
myImages[i] = loadImageToElement('div' + (i+1), imgSrcs[i]);
}
}
<input name="Button1" type="button" value="button" onclick="ft1();" />
Edit: you may want to check for img.complete:
function loadImageToElement(id, imgscr) {
var img = new Image();
var f = function() {
var el = document.getElementById(id);
el.style.backgroundImage = "url(" + imgsrc + ")";
}
img.src = imgscr;
if (img.complete) {
f();
}
else {
img.onload = f;
}
return img;
}
(Note: Image.complete is true, if the image is already cached. In this case the onload-event wont fire in some browsers.)

Categories