I'm currently using the jquery-based iviewer for an online image gallery. This is the code being used to call the initial iviewer source image (edited for brevity):
var $ = jQuery;
$(document).ready(function(){
var iv1 = $(".viewer").iviewer({
src: "/folder/001.jpg",
});
After asking another question elsewhere on SO, I'm currently using this method to drive next/previous buttons by adding '1' to the current image src on click (all images are named incrementally using three digits - 001.jpg, 002.jpg and so on):
var i = 1;
$("#next").click(function()
{
i++;
iv1.iviewer('loadImage', "/folder/" + ("00" + i).slice(-3) + ".jpg");
return false;
});
However, the problem is that elsewhere on the same page I'm using some jquery code to change the displayed image in the iviewer on the basis of the class attribute of the relevant links (which are numbered similarly to the images - chimg001, chimg002 and so on):
$("ul.imageThumbs > li > a").click(function()
{
var k = $(this).attr("class");
iv1.iviewer('loadImage', "/folder/" + ((k).slice(-3)) + ".jpg");
return false;
});
(I'm new to both jquery and javascript so I'm happy to hear any suggested mods to the above.)
After using the above code to display new images, the next and previous buttons don't change relative to the newly-displayed image, but only according to the last image accessed via the next/previous buttons.
I'd like to be able to have the next and previous buttons working by first finding the current src of the iviewer and then add one to that, rather than the current method. Can this be done?
From reading the documentation for the plugin at the link you provided, there are a few parts that may be useful.
info(prop, dropRotation) - get some info about the image. Valid values for prop are: display_width, display_height - current physical dimensions of the image; orig_width, orig_height - dimensions of the original image; angle - current rotation angle; zoom - current zoom value in %; src - url of current image;
All the methods should be called through jquery ui notation: $('#viewer').iviewer('method', 'arg1', 'arg2')
So, try something like this:
$('.iviewer').iviewer('info','src');
Related
I was making an example loading bar using https://source.unsplash.com/ to generate a new image source on a click event.
Source code & example here.
On each button click event I reapplied the src attribute to the image. The image did not change. This same behaviour occurred when creating an image element and applying the src attribute to that, then appending it to the document.
To fix it I generated a random number and applied to to the second dimension at the end of the url on each click event.
Why does this behaviour occur?
A simplified version of what I did first (didn't work):
// onclick = getPhoto()
function getPhoto() {
img.src = 'https://source.unsplash.com/random/3000x3000';
}
What I tried second (worked):
function getPhoto() {
img.src = 'https://source.unsplash.com/random/3000x3000' +
Math.floor(Math.random() * 3000) +
2800;
}
I have a problem with some image change when clicking on a tab.
Problem is with the arrow image, currently its coming with jQuery like this
$('.toggle_title').prepend('<img class="tab-open" src="my_url" />');
So what I need is that, when the tab is open, image changes itself to "tab-close.png" (flipped arrow). Opened tab has an extra class '.toggle_active' (previous class .toggle_title still stays). I have tried something like this, but its not working, can somebody help?
if($('.toggle_title').hasClass('toggle-active')) {
$('.toggle_active').prepend('<img class="tab-open" src="my_url" />')
}
else {
$('.toggle_title').prepend('<img class="tab-open" src="my_url" />')
}
Working with HTML in strings is an anti-pattern. First create an image element:
// You should NOT hardcode this value, this must come from WordPress,
// but that's for a different topic. See `wp_localize_script` to learn more
// http://codex.wordpress.org/Function_Reference/wp_localize_script
var url = 'http://creativeagency.ee/holi/wp-content/themes/bones/library/images/'
var $img = $('<img>', {
'class': 'tab-open',
src: url +'tab-open.png'
})
Next append the image:
$('.toggle_title').prepend($img);
Now, since you have a reference to image, you can easily change its src attribute when you need:
var $title = $('.toggle_title') // chache your elements!
if($title.hasClass('toggle_active')) { // typo!
$img.attr('src', url +'tab-close.png')
} else {
$img.attr('src', url +'tab-open.png')
}
This should help you out, although it is still probably not the perfect abstraction. You may want to have the possible images in an array, and toggle them a different way:
var srcs = ['tab-close.png','tab-open.png']
$img.attr('src', url + srcs[+$title.is('.toggle_active')])
The above does the same but a bit terser, by casting the boolean to a number, and using is instead of hasClass.
i did research for some hours but i can't find anything that is close enough to what I'm looking for. if you know a similar topic, please post the link.
i have not much experience with/in js. i want to create a small simple gallery.
i have a single image on the website. On click the image should be replaced by another one (image2). when i click now on this one, it should be replaced by image3 and so on.
i tried following but this doesn't work at all.
JS
$('.image1').click(function() {
$(this).attr('src', 'image2.jpg');
$(this).addClass('image2');
});
$('.image2').click(function() {
$(this).attr('src', 'image3.jpg');
$(this).addClass('image3');
});
…
when i get the last image (for example "image10"), the gallery should go to the start (image1).
thx for your help
You are looking for something called a Carousel, you have plenty opensource implementations of them on github. One of the most used is Lightbox : https://github.com/lokesh/lightbox2/blob/master/js/lightbox.js
Code is not very long, and you should 'easily' (between quotes :p) find part of it you need for your page.
To show using index() does indeed make sense here you go:
Fiddle
JS Code
$('.image').first().show();
$('.image').on('click', function () {
target = $('.image:visible').index();
lastElem = $('.image').length -1; //2 cause 3 images..
target === lastElem ? target = 0 : target = target + 1;
$('.image').hide()
$('.image').eq(target).show();
});
All images besides the first are initially hidden.
Write something like this. You don't need 10 different event handlers.
Create a common class .. for instance imageClass
$(document).on('click', '.imageClass', function () {
var src = $(this).attr('src'); //image1.png
var index = src.split('.')[0].replace('image',''); //get index `1`
//add 1 to index or reset to first image
index = (index == "10") ? 1 : parseInt(index) + 1;
$(this).attr('src', 'image' + index + '.jpg');
});
The application I'm working on allows users to add an unlimited number of images onto a viewport. With those images, a series of operations are allowed: resize, drag, rotate, and crop. For the cropping feature, I'm using the Jcrop plugin.
When clicking on the control icon for cropping, a lightbox appears, that shows the selected image (the <img> element is one and the same, only the src attribute value changes each time) and allows the user to crop it. The event handler associated triggered when the crop icon is clicked is:
$(document).on("click", "div.cropper", function(){
var ctrl = $(this),
ref = ctrl.attr("reference"),
obj = returnObj(objects,ref),
target = $("#crop-target")
crop_params = {};
target.attr("src",obj.src);
target.Jcrop({
onSelect: function(c){
crop_params = c;
}
});
});
Given the code above, the cropping works perfectly, but ONLY with the first image I try it on. When I click on the "cropper" icon for any other images after that, the first image is shown.
How can I work around this problem?
PS: I've searched through the already existing questions about Jcrop and couldn't find an answer to my particular problem.
You just need to create a new img tag and start jCrop with that.
$('#parent_tag #img_to_crop').remove();
$('#parent_tag').html('<img id="img_to_crop"></img>');
$('#parent_tag #img_to_crop').Jcrop({ options ... });
I want to load only certain images from HTML DOM, based on image width and height.
I dont know how to access the width and height properties of a image using JavaScript.
This must run under any browser.
My app is a bookmarklet, so all the images will be loaded by the time a user will start the bookmarklet. So, i will only scan the DOM, get all the img srv values, and use them. The trick is that i dont want all the images, just the ones that match my wanted sizes.
I have this code so far, and it gets all the images from DOM :
var imgObj = document.getElementsByTagName('img');
for(var i=0;i<imgObj.length;i++)
{
imgsList[i] = imgObj[i].getAttribute('src');
if(consoleLog)console.log(imgsList[i]);
}
return images = imgObj.length;
my problem has been solved here: How to get image size (height & width) using JavaScript?
But i dont know how to adapt my code to img.clientWidth
Is it imgsList[i].clientWidth ?
imgObj[i].clientWidth, imgList contains a list of just the src attributes.
Be careful when using any widths and heights of images as they load asynchronously into the browser. This means that when the DOM loads the width and height will be 0. Only after the images themselves finish loading will the element have a width and height appropriately set.
To get around this you can have load handlers whose callback will be executed once the image finishes loading.
Again though a slightly odd behaviour is that a browser that caches the image will not call this load function again (at least not ones in jQuery) and so you need to make sure for cached versions you do any width checks in a DOM load callback.
You can do this in standard javascript however as an example and since I have a jQuery example in front of me which I was working on earlier I will show you how it can be done in jQuery.
Suppose the image has an id=imageid
function checkWidths() {
//do anything you want here
//jQuery uses the .width and .height functions to get the appropriate attributes of an element, these return a value without the px % etc. To get the actual css use .css('width') instead.
}
$(document).ready(function() {
if($('#imageid').width() > 0)
checkWidths();
});
$('#imageid').load(function() {
checkWidths();
}
To know the dimensions of an image, you need either :
to have the image loaded (then clientWidth is OK if your script is executed in an onload callback)
to have them specified as attributes (<img src=... width=33>). In this case use imgObj[i].getAttribute('width');
Note that if you want to reload an image and avoid all cache problems, the simplest is to change its URL, for example like this :
var srcbase = imgObj.getAttribute('src').split('?')[0];
imgObj.src = srcbase + '?time='+(new Date()).getTime();
(this supposes the image is defined by the path until the '?')
This is it guys, and it works perfect.
populateImgsList : function()
{
var imgObj = document.getElementsByTagName('img');
var j = 0;
for(var i=0;i<imgObj.length;i++)
{
if(consoleLog)console.log('w '+imgObj[i].clientWidth+' h: '+imgObj[i].clientHeight);
if( (imgObj[i].clientWidth>100) && (imgObj[i].clientHeight>100) )
{
imgsList[j] = imgObj[i].getAttribute('src');
if(consoleLog)console.log(imgsList[j]);
j++;
}
}
return images = imgList;
},