I'm playing around with some code which enlarges text based on the size of the div it's in. It can be seen here:
http://codepen.io/anon/pen/zZqXXd
$(function() {
var outer = $('div'), inner = $('h1'),
difference = outer.width()-inner.width(),
ratio = outer.width()/inner.width(),
style = 'translateX(' + difference/2 + 'px) ' + 'scale(' + ratio + ')';
inner.css({'webkit-transform': style, transform: style});
});
However, I'm trying to modify it to use a variable with sizes in, not get it from the div. This was my attempt that doesn't seem to work:
$(function() {
var width = "400",
var inner = $('h1'),
difference = width -inner.width(),
ratio = width /inner.width(),
style = 'translateX(' + difference/2 + 'px) ' + 'scale(' + ratio + ')';
inner.css({'webkit-transform': style, transform: style});
});
You have to replace the comma (',') after var width = "400" with a semicolon. Your current code throws a syntax error.
The corrected code would be:
$(function() {
var width = "400"; // <-----
var inner = $('h1'),
difference = width -inner.width(),
ratio = width /inner.width(),
style = 'translateX(' + difference/2 + 'px) ' + 'scale(' + ratio + ')';
inner.css({'webkit-transform': style, transform: style});
});
Related
I've found a simple example about zooming a HTML image on mouse wheel. Unfortunately in my case I cannot use CSS "transform/translate" and "transformOrigin" because image's position top/left stays the same, but it has to be changed (for example, when the image becomes large enough and reaches left screen side - 'left' position must be "0", not "500px" as in my example).
My code:
<!doctype html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
window.onload = function() {
scale = 1; // scale of the image
xLast = 0; // last x location on the screen
yLast = 0; // last y location on the screen
xImage = 0; // last x location on the image
yImage = 0; // last y location on the image
var mousewheelevt=(/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
if (document.attachEvent) //if IE (and Opera depending on user setting)
document.attachEvent("on"+mousewheelevt, zoomImg)
else if (document.addEventListener) //WC3 browsers
document.addEventListener(mousewheelevt, zoomImg, false)
}
function zoomImg(e){
var evt = window.event || e // equalize event object
var delta = evt.detail? evt.detail*(-120) : evt.wheelDelta // check for detail first so Opera uses that instead of wheelDelta
var imgg = document.getElementById('imgg');
// find current location on screen
var xScreen = e.pageX - imgg.offsetLeft;
var yScreen = e.pageY - imgg.offsetTop;
// find current location on the image at the current scale
xImage = xImage + ((xScreen - xLast) / scale);
yImage = yImage + ((yScreen - yLast) / scale);
// determine the new scale
if (delta > 0)
{
if (scale < 5)
scale += 0.1;
}
else
{
if (scale > 1)
scale -= 0.1;
}
// determine the location on the screen at the new scale
var xNew = (xScreen - xImage) / scale;
var yNew = (yScreen - yImage) / scale;
// save the current screen location
xLast = xScreen;
yLast = yScreen;
imgg.style.transform = 'scale(' + scale + ')' + 'translate(' + xNew + 'px, ' + yNew + 'px' + ')';
imgg.style.transformOrigin = xImage + 'px ' + yImage + 'px';
}
</script>
</head>
<body>
<img id="imgg" src="http://www.baytrail.org/vtour/map4/access/CyteHils/Bayview_Tr_Grn_Hills.JPG" style="position:absolute; top:300px; left:500px;">
</body>
</html>
In my opinion all coefficients are known and I just need to replace these 2 lines to affect position, but I cannot find the right way:
imgg.style.transform = 'scale(' + scale + ')' + 'translate(' + xNew + 'px, ' + yNew + 'px' + ')';
imgg.style.transformOrigin = xImage + 'px ' + yImage + 'px';
How can I do that? If possible, please show an example with CSS "scale" and "zoom" functions.
The following code loops through an array of images and creates them based on the position of Highcharts marker ( a text that is associated with a point on a chart ). It works great in Chrome, FF, IE on desktop but does not work in Safar both Desktop or iOS and even Chrome iOS does not show the images.
The error I am getting is : main.js:453 - TypeError: 'undefined' is not an object (evaluating 'markerOffset.left')
$.each(value, function(k, v){
var z = i;
// Store the current marker
var marker = $('text').filter(function() { if($(this).html() === k) { return $(this) } });
// Get the markers offset
var markerOffset = marker.offset();
// If in Firefox, set the marker height to 13 px
if(marker.height() == 0){
markerHeight = 13;
}
else{
markerHeight = marker.height();
}
// Get the image dimensions
// Create new image object and get the width and height
// The image has to be downloaded first
var img = new Image();
// Set the image location
img.src = v.img;
// When the image is downloaded, you can get the dimensions
img.onload = function(){
var imgHeight = img.height;
var imgDivHeight = img.height;
var imgWidth = img.width;
// If the image Width is more than 90px, resize it
if(imgWidth > 50){
imgDivHeight = imgHeight / (imgWidth / 50);
imgHeight = (imgHeight / (imgWidth / 50)) + 5;
imgWidth = 50;
}
// Create the offset values based on the image sizes
**// THIS IS LINE 453**
var imgLeft = markerOffset.left - ((imgWidth - marker[0].getComputedTextLength()) / 2);
var imgTop = markerOffset.top - (imgHeight - (markerHeight / 4));
// Create an element for each value.img and make it position absolute and set the offset of the marker
$('.charts-inner').prepend('<div class="series-data series-picture-wrapper ' + hidden + ' image-on-chart" data-id="' + k + '" data-series="' + key + '" data-position-top="' + (imgTop - $('.app-ui-top').height() - (markerHeight)) + '" data-position-left="' + (imgLeft - ($('.app-ui-menu').width() + 3)) + '" data-hidden="' + hiddenAttr + '" style="z-index: ' + (5555 + z) + '; top:' + (imgTop - $('.app-ui-top').height() - (markerHeight)) + 'px; left:' + (imgLeft - ($('.app-ui-menu').width() + 3)) + 'px; width:' + imgWidth + 'px; height:' + imgDivHeight + 'px"><img src="' + v.img + '" style="width:' + imgWidth + 'px" /><div class="app-tooltip-stock nodisplay">' + v.tooltip + '</div></div>');
}
})
Right, so the problem was not the OFFSET but that $('text') is an SVG element and in Safari you cant get its content by html().
I changed the filter part to
var marker = $('text').filter(function() {
if($(this)[0].textContent === k) { return $(this) }
});
and it is working now...
I wish to scale the body of my website acording to resolution, but the code not seems to work:
document.body.style.transform: scale(window.screen.availHeight/2);
document.body.style['-o-transform'] = window.screen.availHeight/2;
document.body.style['-webkit-transform'] = window.screen.availHeight/2;
document.body.style['-moz-transform'] = window.screen.availHeight/2;
Try
document.body.style.transform = 'scale(' + window.screen.availHeight/2 + ')';
document.body.style['-o-transform'] = 'scale(' + window.screen.availHeight/2 + ')';
document.body.style['-webkit-transform'] = 'scale(' + window.screen.availHeight/2 + ')';
document.body.style['-moz-transform'] = 'scale(' + window.screen.availHeight/2 + ')';
I'm looking for an effect very similar to this:
http://jsfiddle.net/G5Xrz/
function rnd(max) { return Math.floor(Math.random()*(max+1)) }
function showImage(container, maxwidth, maxheight, imgsrc, imgwidth, imgheight) {
var id = "newimage" + rnd(1000000);
$(container).append(
"<img id='" + id + "' src='" + imgsrc +
"' style='display:block; float:left; position:absolute;" +
"left:" + rnd(maxwidth - imgwidth) + "px;" +
"top:" + rnd(maxheight - imgheight) + "px'>");
$('#' + id).fadeIn();
return id;
}
setInterval(
function() {
showImage("#container", 400, 600,
"http://placekitten.com/" + (90 + rnd(10)) + "/" + (90 + rnd(10)),
100, 100);
}, 700);
But i'd prefer a flexible layout, ie images not bound by a div with predefined height and width, instead responding to the dimensions of the browser.
The following piece of code seems to have a more appropriate way of generating the random positions:
http://jsfiddle.net/Xw29r/15/
function makeNewPosition(){
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
function animateDiv(){
var newq = makeNewPosition();
var oldq = $('.a').offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$('.a').animate({ top: newq[0], left: newq[1] }, speed, function(){
animateDiv();
});
};
However I'm very much a beginner with javascript and I don't know how to combine the two.
Can anyone help?
Thanks
Take this part from the second code:
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
and use those variables h and w with the browser height and width (minus 50) as the appropriate parameters in this part of the first code:
setInterval(
function() {
showImage("#container", 400, 600,
"http://placekitten.com/" + (90 + rnd(10)) + "/" + (90 + rnd(10)),
100, 100);
}, 700);
Also, the first code has this HTML:
<div id="container" style="width:400px; height:600px; background: green; position:relative"></div>
That hard-codes the height and width at pixel values. You can use a CSS percentage value to make the width respond to the parent container's size. However, you will need JS to set the height properly; a percentage for the height does nothing
Putting that all together (and removing the "minus 50" part), you get this:
jsFiddle demo
<div id="container" style="width:100%; height:100px; background: green; position:relative"></div>
function adjustContainerHeight(height) {
$('#container').height(height);
}
adjustContainerHeight($(window).height());
setInterval(
function() {
var h = $(window).height();
var w = $(window).width();
adjustContainerHeight(h);
showImage("#container", w, h,
"http://placekitten.com/" + (90 + rnd(10)) + "/" + (90 + rnd(10)),
100, 100);
}, 700);
This updates the height of the container when the page is first loaded, and once again whenever the random image is placed. More robust code would have a separate height-adjusting event handler that updates the height whenever the page size changes.
Ok, so I am trying to use jQuery to get the innerWidth() of an element #preview. I want to create a conditional that says IF x offset LEFT + #preview width is greater than page width, give it style right: z where z = #preview width + xOffset.
I apologize my code below is a mess and the syntax for .css ("right", (rightFloat + xOffset) + "px") (line 125) is off, but that's part of my problem.
<script>
$(document).ready(function(){
//append "gallery" class to all items with "popup" class
imagePreview();
$(".popup").addClass("gallery");
});
//The overlay or pop-up effect
this.imagePreview = function() { /* CONFIG */
xOffset = 40;
yOffset = 40;
// these 2 variable determine popup's distance from the cursor
// you might want to adjust to get the right result
/* END CONFIG */
$("a.preview").click(function(e) {
return false;
});
$("a.preview").hover(function(e) {
this.t = this.title;
this.title = "";
var c = (this.t != "") ? "<br/>" + this.t : "";
var rightFloat = e.pageX + ("#preview").innerWidth;
$("body").append("<p id='preview'><img src='" + this.href + "' alt='Image preview' />" + c + "</p>");
$("#preview").hide().css("top", (e.pageY - yOffset) + "px").css("left", (e.pageX + xOffset) + "px").fadeIn("2000");
while ((left + 400) > window.innerWidth) {.css("right", (rightFloat + xOffset) + "px")
}
}, function() {
this.title = this.t;
$("#preview").remove();
});
$("a.preview").mousemove(function(e) {
var top = e.pageY - yOffset;
var left = e.pageX + xOffset;
var rightFloat = e.pageX + ("#preview").innerWidth;
//flips the image if it gets too close to the right side
while ((left + 400) > window.innerWidth) {.css("right", +(rightFlaot + xOffset) + "px")
}
$("#preview").css("top", top + "px").css("left", left + "px");
});
};
</script>
Try using http://api.jquery.com/offset/
if($('#preview').offset().right<0){
var right = parseInt($(window).width()) - e.pageX + xOffset;
$("#preview").css("top", top + "px").css("right", right + "px");
}else{
var left = e.pageX + xOffset;
$("#preview").css("top", top + "px").css("left", left + "px");
}
I made these fixes because I couldn't get your code to work in jsfiddle:
var xOffset = 40;
var yOffset = 40;
$("a.preview").bind('mouseover',function(e){
var rightFloat = parseFloat(e.pageX)+$("#preview").innerWidth();
var ptop = parseFloat(e.pageY) - yOffset;
var pleft = parseFloat(e.pageX) + xOffset;
$("#preview").css({"top":ptop + "px","left":pleft + "px"});
});
There's the fixes for the top half but I have no idea what you're trying to do with the bottom part (with the while loop). Can you explain what functionality you want?