Propagation of Script - javascript

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.

Related

JS - Get new element after click event

I'm working on a chrome extension to automate some work of mine. Currently it enters a value into a input, then clicks the button.
I want to get a new div element when it gets to the next page (once loaded). But it always looking a div before click event.
I hope that you understanded my problem.
Here is a code:
bSzukaj.onclick = function()
{
var url = "/game.php?screen=place";
var coords = [];
var loaded = false;
var n = inputZakres.value;
var x = parseInt(inputPobierz.value.split("|")[0] - parseInt(n/2+1));
var y = parseInt(inputPobierz.value.split("|")[1] - parseInt(n/2+1));
var newWindow = window.open(url);
var currentX = x;
var currentY = y;
var coord = currentX+"|"+currentY;
var sender = newWindow.addEventListener('load', function(){
var spearInput = newWindow.document.getElementById("unit_input_spear");
spearInput.value = 10;
var coordClass = newWindow.document.getElementsByClassName("target-input-field target-input-autocomplete")[0];
coordClass.value = coord;
var send = newWindow.document.getElementById("target_attack").click();
// NOW SCRIPT RELOAD PAGE AND CREATING SOME COMUNICATS
// AND I WANT TO GET THIS COMUNICATS TO VARIABLE
// BUT EVEN THIS ALERT BELOW DOESN'T WORK :/
newWindow.addEventListener('load', function() {
alert("now");
});
}, false);
//}
//}
}
}

Send pictures to a new window

I'm trying to make a slideshow of pictures and send them to an another window. But after selecting images and pressing the button for showing slideshows, nothing happens. I'm using firebug to detect bugs and when I'm going wrong. But I'm not getting any error from firebug so I gotta ask you guys. This is my code.
var infoBox;
var formTag;
var imgUrlList;
var imgTextList;
var windVar;
var urlList;
var textList;
function init() {
var i;
infoBox = document.getElementsByClassName("outerBox");
for (i=0; i<infoBox.length; i++) {
infoBox[i].onmouseover = showInfoBox;
infoBox[i].onmouseout = hideInfoBox;
}
formTag = document.getElementsByTagName("input");
for (i=0; i<formTag.length; i++) {
formTag[i].onclick = checkedBox;
}
windVar = null;
imgTextList = [];
imgUrlList = [];
}
window.onload = init;
function showInfoBox() {
var showInfo;
showInfo = this.getElementsByClassName("innerBox")[0];
showInfo.style.visibility = "visible";
}
function hideInfoBox() {
var hideInfo;
hideInfo = this.getElementsByClassName("innerBox")[0];
hideInfo.style.visibility = "hidden";
}
function checkedBox() {
var ImgNode, ImgTag;
for (i=0; i<formTag.length; i++) {
imgNode = this.parentNode.parentNode.firstChild;
imgTag = imgNode.nextSibling
if (this.checked) {
imgTag.className = "markedImg";
}
else {
imgTag.className = "unmarkedImg";
}
}
}
function slideShowBtn() {
var url, i, filename;
imgUrlList.length = 0;
imgTextList.length = 0;
for (i=0; i<formTag.length; i++) {
if (formTag.checked) {
url = infoBox.firstChild.getElementsByTagName("img")[i].src;
filename = infoBox.firstChild.getElementsByTagName("span")[i].src;
imgUrlList.push(url);
imgTextList.push(filename);
}
else break;
}
newWindow(700,600,"slideshow.htm");
}
function newWindow(width,height,fileName) {
var windProporties;
windProporties = "top=100, left=100,toolbar=no,status=no,menubar=no,scrollbars=no,resizable=no,width=" + width + ",height=" + height;
if (windVar != null) if (windVar.closed == false) windVar.close();
windVar = window.open(fileName,"bildspel",windProporties);
}
The formTag variabel is from a checkbox-input-tag. And it's from that I decide which pictures are selected and will be moved to the new page. ImgTextList and imgUrlList are global variables that'll also be in the next window. infoBox is a reference to a div class which is called OuterBox and inside it is an another div-class named innerBox, it's in the innerBox classdiv which the img and span-tags are. The code for the slideshow is already written and I'm just writing code for sending the variables to it.
Edit: I should have been a little more informative. But here's the code for the slideshow part where window.opener is present. And I've added all the remaining code that's above. How do you embed files?
// JavaScript for the slideshow page
// ----- Global variables -----
var imgUrlList = window.opener.imgUrlList; // Array with filenames of selected images. Initialized to an empty array.
var imgTextList = window.opener.imgTextList; // Array with image texts of selected images. Initialized to an empty array.
var slideshowMenu = null; // Reference to the image menu.
var slideshowImg = null; // Reference to the slideshow img tag.
var slideshowText = null; // Reference to the tag for the image text.
// ---- Create the image menu and show the first image. Also attach event handlers. ----
function initSlideshow() {
// Create a image list from the content of the variable imgUrlList
var HTMLcode = "<select id='imgMenu'>";
for (var i=0; i<imgTextList.length; i++) {
HTMLcode += "<option>" + imgTextList[i] + "</option>";
} // End for
HTMLcode += "</select>";
document.getElementById("iMenu").innerHTML = HTMLcode; // Add the select and option tags to the HTML code
slideshowMenu = document.getElementById("imgMenu"); // Save a reference to the menu's select tag
slideshowMenu.selectedIndex = 0; // Select the first option in the menu
slideshowImg = document.getElementById("slideshowBox").getElementsByTagName("img")[0];
slideshowText = document.getElementById("slideshowBox").getElementsByTagName("div")[0];
// Show the first image
slideshowImg.src = imgUrlList[0];
slideshowText.innerHTML = imgTextList[0];
// Attach event handlers
var slideshowButtons = document.getElementById("slideshowForm").getElementsByTagName("input");
slideshowButtons[0].onclick = showPrevImage;
slideshowButtons[1].onclick = showNextImage;
slideshowMenu.onchange = showSelectedImage;
} // End initSlideshow
window.onload = initSlideshow;
// ---- Show previous image in the list (menu) ----
function showPrevImage() {
var ix = slideshowMenu.selectedIndex; // Index for the current image
if (ix > 0) { // If it's not already the first image
slideshowMenu.selectedIndex = ix-1;
slideshowImg.src = imgUrlList[ix-1];
slideshowText.innerHTML = imgTextList[ix-1];
}
} // End showPrevImage
// ---- Show next image in the list (menu) ----
function showNextImage() {
var ix = slideshowMenu.selectedIndex; // Index for the current image
if (ix < slideshowMenu.length-1) { // If it's not already the last image
slideshowMenu.selectedIndex = ix+1;
slideshowImg.src = imgUrlList[ix+1];
slideshowText.innerHTML = imgTextList[ix+1];
}
} // End showNextImage
// ---- Show selected image in the list (menu) ----
function showSelectedImage() {
var ix = slideshowMenu.selectedIndex; // Index for the selected image
slideshowImg.src = imgUrlList[ix];
slideshowText.innerHTML = imgTextList[ix];
} // End showSelectedImage
Um, you never do anything to send it. Either pass it as a querystring parameter or have the child reference a global variable in the opener.
var foo = window.opener.imgUrlList;

JavaScript Image().width returns 0

I need to get width and height of images with display:none and I'm getting both width and height 0.
here's my code:
for (i = 0; i <= slideCount; ++i) {
imgPath = slideshow.eq(i).attr("src");
imgEle = new Image();
imgEle.src = imgPath;
imgEle.addEventListener("load", function () {
imgSize = [imgEle.width, imgEle.height];
if ((imgSize[0]/imgSize[1]) > (boxSize[0]/boxSize[1])) {
slideshow.eq(i).css("height", "100%");
}
else {
slideshow.eq(i).css("width", "100%");
}
});
}
I tried onload = funcion() {} approach as well as not checking if image is loaded, yet still I'm getting width and height as 0. What's more when i launched console on Chrome and referred to those fields I got proper values.
It is because of the wrong use of closure variable in a loop, when the load handler is executed the variable imgEle refers to the last image object reference, not the one on which the load event was called, so when the first element is loaded the last element might not have been loaded so imgEle.width/imgEle.height will return 0
Instead you can use this which will refer to the element on which the load event was called inside the load event handler
From what I can see, what you need is
slideshow.each(function () {
var $this = $(this);
var imgPath = $this.attr("src");
var imgEle = new Image();
imgEle.src = imgPath;
imgEle.addEventListener("load", function () {
var imgSize = [this.width, this.height];
if ((imgSize[0] / imgSize[1]) > (boxSize[0] / boxSize[1])) {
$this.css("height", "100%");
} else {
$this.css("width", "100%");
}
});
})
Note: the array index runs from 0...length-1 so your loop condition <= slideCount; might have to be relooked at
imgEle is overwritten each time your loop runs. Wrap an anonymous function around it to prevent this issue.
for(var i = 0; i <= slideCount; ++i) {
(function(i){
var imgPath = slideshow.eq(i).attr("src");
var imgEle = new Image();
imgEle.src = imgPath;
imgEle.addEventListener("load", function () {
imgSize = [imgEle.width, imgEle.height];
if ((imgSize[0]/imgSize[1]) > (boxSize[0]/boxSize[1])) {
slideshow.eq(i).css("height", "100%");
}
else {
slideshow.eq(i).css("width", "100%");
}
});
})(i);
}

Adding a counter to a prev/next image slideshow(javascript/css only)?

I have created a "prev/next" slideshow using javascript, now I want to add a counter(1/10, 2/10, 3/10...) beside my "prev/next" buttons but nothing seemed to work.
This is my first time attempting to make a website, I know nothing about jQuery, so please stick with html+javascript if possible. Here is my script
var image = new Array(
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/_MG_7747.jpg",
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/1109163s.jpg")
var imgNumber=1
var numberOfImg=2
function previousImage(){
if(imgNumber>1){
imgNumber--
}
else{
imgNumber = numberOfImg
}
document.slideImage.src = image[imgNumber-1]
}
function nextImage(){
if(imgNumber < numberOfImg){
imgNumber++
}
else{
imgNumber = 1
}
document.slideImage.src = image[imgNumber-1]
}
if(document.images){
var image1 = new Image()
image1.src = "http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/_MG_7747.jpg"
var image2 = new Image()
image2.src = "http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/1109163s.jpg"
}
Script+html: http://jsfiddle.net/nLHY9/5/
(Prev/Next buttons seem not to be working on this----they work fine when I launched them from laptop to browser.)
you could have used some existing javascript image sliders, for example, sliderman slider, for your current code, you can do like, add an element like span, to hold the count, and you could add a function like:
function changeCounter(cur, total) {
document.getElementById("counter").innerHTML = cur + "/" + total;
}
and call it in your previousImage() and nextImage() functions, as in this demo jsfiddle
There are many pure css slideshows that are beautiful and can do impressive things. However, as you try to support older browsers, the pure css slideshows get less and less impressive or even impossible. JavaScript is the most flexible and powerful way to go. That being, I wanted to help you clean up your code. I only had a few minutes, so this is a quickly thrown together plugin, but it should get you on the right track.
First, a few notes on your code:
//you're missing semicolons everywhere. ";"
/* "var image" is very unclear.
* it's an array, so it should be plural "images"
* there aren't images in this array - it's image urls or sources
* instead of "new Array" you could just use "[]"
*/
var image = new Array(
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/_MG_7747.jpg",
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/1109163s.jpg")
var imgNumber=1 //the name doesn't mean anything. I have to assume that you mean "currentImgNumber" or something to that effect
var numberOfImg=2 //this could be determined by checking the length of your array - myArray.length
And here's my exampe plugin:
Live demo here (click).
/***** This section is how you use the plugin. I start writing with the usage and then I make it mean something *****/
window.onload = function() { //when the page is loaded
var fooElem = document.getElementById('foo'); //get an element where we will attach the plugin
var foo = Object.create(slideshow); //create a new slideshow object
foo.create({ //create a slideshow with the given options
element: fooElem, //the element where the slideshow will be
sources: [ //image urls
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/_MG_7747.jpg",
"http://i990.photobucket.com/albums/af24/callmeaaaaj/AJ/1109163s.jpg"
]
});
//we can make more of these and with different options
var barElem = document.getElementById('bar');
var bar = Object.create(slideshow);
bar.create({
element: barElem,
sources: [
"http://eggboss.com/wp-content/uploads/2013/09/The-Gentleman-233x300.png",
"http://fc07.deviantart.net/fs71/f/2013/040/8/a/profile_picture_by_classy_like_a_sir-d5uf426.jpg"
]
});
};
/**** now let's create the plugin and make it work as it is used above *****/
var slideshow = {
currentIndex: 0,
imgs: [],
create: function(options) {
options.element.className+= ' slideshow'; //add a class to the main element for styling
this.imgs = this.getImgs(options.sources); //make img html
var controls = this.getControls(); //make controls
//add the html to the element from the options
var frag = document.createDocumentFragment();
this.imgs.forEach(function(img) {
frag.appendChild(img);
});
frag.appendChild(controls);
options.element.appendChild(frag);
},
getImgs: function(sources) {
var imgs = [];
sources.forEach(function(src, i) {
var img = document.createElement('img');
img.src = src;
imgs.push(img);
if (i > 0) {
img.style.display = 'none'; //hide all but first image
}
});
return imgs;
},
getControls: function() {
var that = this; //so that we can access "this" within the click functions
var controls = document.createElement('div');
controls.className = 'controls';
var counter = document.createElement('span');
counter.className = 'counter';
this.setCounter(counter);
var prev = document.createElement('a');
prev.textContent = 'Prev';
prev.className = 'prev';
prev.addEventListener('click', function() {
newIndex = (that.currentIndex) ? that.currentIndex-1 : that.imgs.length-1;
that.changeImg(newIndex, counter);
});
var next = document.createElement('a');
next.textContent = 'Next';
next.className = 'next';
next.addEventListener('click', function() {
newIndex = (that.currentIndex !== that.imgs.length-1) ? that.currentIndex+1 : 0;
that.changeImg(newIndex, counter);
});
controls.appendChild(prev);
controls.appendChild(next);
controls.appendChild(counter);
return controls;
},
changeImg: function(newIndex, counter) {
this.imgs[this.currentIndex].style.display = 'none';
this.imgs[newIndex].style.display = 'inline';
this.currentIndex = newIndex;
this.setCounter(counter);
},
setCounter: function(counter) {
counter.textContent = (this.currentIndex+1)+' / '+this.imgs.length;
}
};

Detect img src and then change it with 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

Categories