global variable gives "undefined" in jQuery - javascript

I have to functions that execute when two different <img> are clicked on. I have to communicate a variable between them.
Getting rid of the irrelevant code, what I have looks something like this:
var size=0;
$('#gallery img').click(function(){
window.size = $('#lightbox img').attr('data-size');
});
$('#lightbox i').click(function(){
var dest=window.size-1;
});
But, when I go to the javascript console, and type size, I get undefined.

Replace
window.size
With
size
because its javascript custom variable not a window object property
EDIT
var size=0;
$('#gallery img').click(function()
{
size = $('#lightbox img').attr('data-size');
});
$('#lightbox i').click(function()
{
var dest = size-1;
alert(dest);
alert(size);
});
above code will alert 0 and -1 if you first click on #ligtbox i now if you first click on #gallery img then it will alert result depending on click you made.

Change
window.size
to
size
and $('#lightbox img').attr('data-size');
to
$('#lightbox img').data('size');

Related

Change class on multiple img in array

This is my first post here, I always found solutions on this page, so thank you for that.
I have a problem with .removeClass and .addClass in my last program.
I load multiple pictures into array Frames and I want change all (previous-image) to (current-image) in frames[0]. Here is my code, it is change class only on second image. Here is code:
function loadImage() {
// Creates a new <li>
var li = document.createElement("li");
// Generates the image file name using the incremented "loadedImages" variable
var imageName = "graphics/img/Dodge_Viper_SRT10_2010_360_720_50-" + (loadedImages + 1) + ".jpg";
var imageName1 = "graphics/img/Dodge_Viper_SRT10_2010_360_720_50-" + (loadedImages + 1) + ".jpg";
/*
Creates a new <img> and sets its src attribute to point to the file name we generated.
It also hides the image by applying the "previous-image" CSS class to it.
The image then is added to the <li>.
*/
var image = $('<img>').attr('src', imageName).addClass("previous-image").appendTo(li) && $('<img>').attr('src', imageName1).addClass("previous-image light-image").appendTo(li);
// We add the newly added image object (returned by jQuery) to the "frames" array.
frames.push(image);
// We add the <li> to the <ol>
$images.append(li);
/*
Adds the "load" event handler to the new image.
When the event triggers it calls the "imageLoaded" function.
*/
$(image).load(function() {
imageLoaded();
});
};
function imageLoaded() {
// Increments the value of the "loadedImages" variable
loadedImages++;
// Updates the preloader percentage text
$("#spinner span").text(Math.floor(loadedImages / totalFrames * 100) + "%");
// Checks if the currently loaded image is the last one in the sequence...
if (loadedImages == totalFrames) {
// ...if so, it makes the first image in the sequence to be visible by removing the "previous-image" class and applying the "current-image" on it
frames[0].removeClass("previous-image").addClass("current-image");
/*
Displays the image slider by using the jQuery "fadeOut" animation and its complete event handler.
When the preloader is completely faded, it stops the preloader rendering and calls the "showThreesixty" function to display the images.
*/
$("#spinner").fadeOut("slow", function() {
spinner.hide();
showThreesixty();
});
} else {
// ...if not, Loads the next image in the sequence
loadImage();
}
};
This is, how it looks in browser:
<ol><li><img src="graphics/img/Dodge_Viper_SRT10_2010_360_720_50-1.jpg" class="previous-image"><img src="graphics/img/Dodge_Viper_SRT10_2010_360_720_50-1.jpg" class="light-image current-image"></li></ol>
This is, what I want:
<ol><li><img src="graphics/img/Dodge_Viper_SRT10_2010_360_720_50-1.jpg" class="current-image"><img src="graphics/img/Dodge_Viper_SRT10_2010_360_720_50-1.jpg" class="light-image current-image"></li></ol>
When I change this
var image = $('<img>').attr('src', imageName).addClass("previous-image").appendTo(li) && $('<img>').attr('src', imageName1).addClass("previous-image light-image").appendTo(li);
to this
var image = $('<img>').attr('src', imageName1).addClass("previous-image light-image").appendTo(li) && $('<img>').attr('src', imageName).addClass("previous-image").appendTo(li);
it still change only second img. Any help?
var image = $('<img>').attr('src', imageName).addClass("previous-image").appendTo(li) && $('<img>').attr('src', imageName1).addClass("previous-image light-image").appendTo(li);
is not doing what you think it is. It's only using the second element you declare. They both get appended to the page (because the appendTo method runs), but && is a logical operator, it's not used for concatenation, so the variable "image" only contains the second image you declared.
This will work instead:
var image = $('<img>', { "src": imageName, "class": "previous-image" });
image = image.add($('<img>', { "src": imageName1, "class": "previous-image light-image" }));
image.appendTo(li);
If you are just trying to replace all the previous-image classes with current image then you can do this:
$('img.previous-image').each(function(){
$(this).addClass("current-image").removeClass("previous-image");
});

Javascript: Display clickable images at the end of each paragraph

$(document).ready(function(){
function createPopup(event){
$('<div class="popup"><img src="mysrc.jpg" img style="opacity=0.5; width:50px; height:50px;"></img></div>').appendTo('body');
positionPopup(event);
};
function positionPopup(event){
var tPosX = 950;
var tPosY = event.clientY+25;
$('div.popup').css({'position': 'absolute', 'top': tPosY, 'left':tPosX});
$('#test').attr('ydown', parseInt(tPosY)+ parseInt(add));
};
var elements = document.getElementsByTagName('cposs');
for(var i = 0; i < elements.length; i++){
var imagetest = document.createElement("img");
imagetest.src = "mysrc.jpg";
elements[i].onmouseover = function(){
this.style.background = 'Green';
createPopup(event);
}
elements[i].onmouseout = function(){
this.style.background = '';
}
var ycoor= $('#test').attr('ydown');
$( "#test" ).append( "<a href=http://www.google.com><img src='mysrc.jpg'</img></a>" );
}
});
</script>
<div id="test" ydown="<?php echo $ydown; ?>" xdown="<?php echo $xdown; ?>">
There is then multiple paragraphs with <cposs></cposs> tags and this allows the text to be highlighted when the mouse is hovered over and creates a popup image to the right of the paragraph. I also have for each counted <cposs></cposs> an image that is displayed in the test div.
There is a couple things I was hoping I would be able to accomplish:
On page load, I would like an image to be displayed at the end of each <cposs></cposs> text. Instead of fixed coordinates.
I would like these images to execute a function when clicked on.(Tried adding the "onclick" attribute but said the function was not defined)
Eventually, I would like the clickable images to cause the text between the cposs tags to highlight. Similar to what I have now, but instead of mouse over, its a click event.
EDIT:
I have tried to add an onclick attribute to the appended image but once the image is clicked, says the function is not defined.
I am unsure on how to get the coordinates of the cposs tags. I am confused on if I am able to use offset and or position function in javascript. I have attempted to use both and have not succeeded.
I guess all I really need to know if how to get the end coordinates of the cposs tags and how to give each displayed image a clickable function
I am a big fan of jsfiddle!
Any sort of help is greatly appreciated!
Thanks in advance.
Here's a jsFiddle example: https://jsfiddle.net/sn625r3z/14/
To make freshly added elements clickable you should be using jQuery's ".on" function and pass an event to it. Something like this:
$('img.new-image').on('click', function(){
$(this).parent().css({background: 'green'});
});
In the jsFiddle example I positioned images with CSS. But if you want to get the coordinates to position the image at the end of the block I would do it like this:
$('cposs').each(function(){
var el = $(this);
var width = el.width();
var height = el.height();
var newElement = $('<img class="new-image" src="'+imagetest.src+'" />');
el.append(newElement);
newElement.css({top: height+"px", left: width+"px"});
});
Hope this helps.

How to execute jquery when a variable with a CSS property changes

I need to set the scrollleft back to 0 on my wrapper when a specific css property changes. I'm a bit new to jquery and have never used variables, but I'm assuming that I'll need to declare the somewhat complex variable before the function, and then execute the function when the variable changes. Am I correct? It needs to continually respond like this to resize queries. This will be an epic solution for me if it works!
var changer = $(".dummy").css("float"); //whatever the float property is
$(document).ready(){
$(window).resize(function(){
if ($(".dummy").css("float") != changer ){
$(".wrapper").scrollLeft(0);
}
});
here is my suggestion: Use an ID for "dummy", if you have more than one "dummy" in your dom-tree you get an array with html elements from jquery.
$(document).ready(function() {
// First init for "dummy"
var $dummy = $("#dummy"),
dummyFloat = $dummy.css("float");
$(window).resize(function () {
var dynamicDummyFloat = $dummy.css("float");
if (dynamicDummyFloat != dummyFloat) {
$(".wrapper").scrollLeft(0);
dummyFloat = dynamicDummyFloat;
}
});
});
The code that you have written will work fine.

Jquery click function inside each loop

When I click .zoom in this example, I inject 20 (the amount of items in the loop) .big_image divs. I'd just like to insert one, relative to the item I am clicking.
$('.main img').each(function() {
var img = this;
$('.zoom').click(function() {
$(this).after('<div class="big_image"><img src="'+$(img).attr('src')+'"></div>');
});
});
I have simplified the script right down here. Ideally I'd just like to know how to modify the click function (if possible) as there are other things going on not related to the question. Thanks!
EDIT: Working example here.
The zoom button should appear on at least the first 2 images in the gallery (top left corner). If it's confusing, I'm trying to get the zoom button to only appear on very long/tall images. I'm also aware that I should split the setClass function up but haven't learned how to do that yet :)
$('.zoom').click(function(e){
var imgURL= $(this).parents('.main').find('img').attr('src');
$(this).after('<div class="big_image"><img src="'+imgURL+'"></div>')
});
if .main container is the immediate parent of both the img and .zoom you can use
var imgURL= $(this).siblings('img').attr('src');
if it HAS to be inside the loop. try modifying your code like below
var flag=false;
$('.main img').each(function() {
var img = this;
$('.zoom').click(function() {
if(!flag)
$(this).after('<div class="big_image"><img src="'+$(img).attr('src')+'"></div>');
flag=true;
});
});
The person who answered this removed their answer for some reason! The key is .next()
var img = this;
$(this).next('.zoom').click(function() {
$(this).after('<div class="big_image"><img src="'+$(img).attr('src')+'"></div>');
});

How can i know if all <img> loaded in div using jQuery

How can i know if all loaded in div using jQuery
i want to do this after load all img in #slider div
var imgHeight = $("#slider img").height();
alert(imgHeight);
You can use the load event
$('#slider img').load(function(){
var imgHeight = $(this).height();
alert(imgHeight);
});
if there are more than one image, and you only want to obtain the height after they have all loaded, try this code
var img = $('#slider img');
var length = img.length;
img.load(function(){
length--;
if(length === 0){
alert("All images loaded");
};
});
Well, I've tested the code, and it appears that the problem hasn't got anything to do with the code. When loading the page with the images already in the cache, this is what I get:
Strangely, this does not occur when I force the browser not to use the cache.
Try this:
Attach an onload event listener to each image in the slider.
In the listener:
Give the current image a custom attribute to mark it is 'ready'.
Check if all images are ready. If so, do your thing (i.e. alert(imageHeight))
untested:
(function(){
var slider=document.getElementById('slider'),
images=slider.getElementsByTagName('img'), image, i=-1;
while (image=images[i]) {
image.onload=function(){
this['data-ready']=true;
var image, i=-1;
while (image=images[i]) if (!image['data-ready']) return;
// all images are ready; do your thing here
// ...
}
}
}());

Categories