I have made a simple zoom in and out function with button as well as mousewheel function. The main concept is to limit the maximum zoom level and minimum zoom level.
I have successfully made it in two ways
BIN 1
BIN 2
But i tried to make this in a tab section with unique ID or by class.
My script
var zoomLevel = 100;
var maxZoomLevel = 150;
var minZoomLevel = 50;
var initW=0,initH=0;
function zoom(zm) {
var img=document.getElementById("pic");
if(zm > 1){
if(zoomLevel < maxZoomLevel){
zoomLevel+=10;
}else{
return;
}
}else if(zm < 1){
if(zoomLevel > minZoomLevel){
zoomLevel-=10;
}else{
return;
}
}
img.style.width = (initW*zoomLevel/100)+"px";
img.style.height = (initH*zoomLevel/100)+"px";
img.style.marginLeft = ((initW-img.width)/2) + "px";
img.style.marginTop = ((initH-img.height)/2) + "px";
}
window.onload=function(){
var img=document.getElementById("pic");
initW=img.width;
initH=img.height;
img.onmousewheel=function(e){
e=e||window.event;
if(e.wheelDelta>=120) zoom(1.1);
else zoom(0.9);
};
if(/Firefox/.test(navigator.userAgent)){
img.addEventListener("DOMMouseScroll",function(e){
if(e.detail<0) zoom(1.1);
else if(e.detail>0) zoom(0.9);
e.preventDefault();
},false);
}
};
Here i am getting my element by using GetElementById to access my image tag is there any way to get access all the img tags in other tabs too.
I also tried getElementsbyClassName but its not working it just retrieving the nodeslist.
How can i access all three images here
Current BIN
you need to use different ID's
var img=document.getElementById("pic1");
var img=document.getElementById("pic2");`
You have assigned all three images the same id (id="pic"). You can't do that, ids must be unique.
If you change their ids, (ex: pic, pic2, pic3), and pass that in to your zoom function as an argument, then all the tabs will zoom.
So change the zoom function to look like this:
function zoom(zm, id) {
var img=document.getElementById(id);
...
}
And make your html look like this (just one for an example):
<div id="tabs-2">
<input type="button" value ="-" onClick="zoom(0.9, 'pic2')"/>
<input type="button" value ="+" onClick="zoom(1.1, 'pic2')"/>
<div id="thediv">
<img id="pic2" src="http://stereo-ssc.nascom.nasa.gov/beacon/t0193.jpg"/>
</div>
</div>
Now all three will zoom individually. Here's a jsbin showing it.
But, there's a bug. The variable you use to track the zoom state is being shared between the tabs. This means the "zoom limit" is not really enforced: you can just zoom one tab all the way down, then the next tab all the way up. Repeat this to make any of the images as big or as small as you want. I don't think this is what you want, but I'm going to leave it an exercise for you to fix.
Related
I have an image - image1.png. When I click a button the first time, I want it to change to image2.png. When I click the button for a second time, I want it to change to another image, image3.png.
So far I've got it to change to image2 perfectly, was easy enough. I'm just stuck finding a way to change it a second time.
HTML:
<img id="image" src="image1.png"/>
<button onclick=changeImage()>Click me!</button>
JavaScript:
function changeImage(){
document.getElementById("image").src="image2.png";
}
I'm aware I can change the image source with HTML within the button code, but I believe it'll be cleaner with a JS function. I'm open to all solutions though.
You'll need a counter to bump up the image number. Just set the maxCounter variable to the highest image number you plan to use.
Also, note that this code removes the inline HTML event handler, which is a very outdated way of hooking HTML up to JavaScript. It is not recommended because it actually creates a global wrapper function around your callback code and doesn't follow the W3C DOM Level 2 event handling standards. It also doesn't follow the "separation of concerns" methodology for web development. It's must better to use .addEventListener to hook up your DOM elements to events.
// Wait until the document is fully loaded...,
window.addEventListener("load", function(){
// Now, it's safe to scan the DOM for the elements needed
var b = document.getElementById("btnChange");
var i = document.getElementById("image");
var imgCounter = 2; // Initial value to start with
var maxCounter = 3; // Maximum value used
// Wire the button up to a click event handler:
b.addEventListener("click", function(){
// If we haven't reached the last image yet...
if(imgCounter <= maxCounter){
i.src = "image" + imgCounter + ".png";
console.log(i.src);
imgCounter++;
}
});
}); // End of window.addEventListener()
<img id="image" src="image1.png">
<button id="btnChange">Click me!</button>
For achieve your scenario we have to use of counter flag to assign a next image. so we can go throw it.
We can make it more simple
var cnt=1;
function changeImage(){
cnt++;
document.getElementById("image").src= = "image" + cnt + ".png";
}
try this
function changeImage(){
var img = document.getElementById("image");
img.src = img.src == 'image1.png' ? "image2.png" : "image3.png";
}
Just use an if statement to determine what the image's source currently is, like so:
function changeImage(){
var imageSource = document.getElementById("image").src;
if (imageSource == "image1.png"){
imageSource = "image2.png";
}
else if (imageSource == "image2.png"){
imageSource = "image3.png";
}
else {
imageSource = "image1.png";
}
}
This should make the image rotate between 3 different image files (image1.png, image2.png and image3.png). Bear in mind this will only work if you have a finite number of image files that you want to rotate through, otherwise you'd be better off using counters.
Hope this helps.
Check the below code if you make it as a cyclic:
JS
var imgArray = ["image1.png", "image2.png", "image3.png"];
function changeImage(){
var img = document.getElementById("image").src.split("/"),
src = img[img.length-1];
idx = imgArray.indexOf(src);
if(idx == imgArray.length - 1) {
idx = 0;
}
else{
idx++;
}
document.getElementById("image").src = imgArray[idx];
}
html
<button onclick=changeImage();>Click me!</button>
function changeImage(){
document.getElementById("image").attr("src","image2.png");
}
I want to remove/add classes when the user is at different distances from the top by using jQuery.
I have successfully done it, and it works fine, but I think I'm doing it wrong, and I would like your help to optimize the code.
The html is simple, basically the sections(including the header), have 100% width. and different colors. I want to make the header change color when its over the first section(for aesthetical purposes).
And I also want it to have a shadow when the page has been scrolled more than 1 pixel.
I'm doing it by adding/removing classes.
When I use one big else if statement it doesn't work well because whenever any any condition is matched js stops checking for other matches, so it doesn't apply all the classes needed.
The next code works, however as I said, I think that it's not optimal/bad written.
Here is the HTML markup:
<header class="dark no-shadow">
Header
</header>
<section class="blue">
Please Scroll Down to see the header changes...
</section>
<section>
The header color Should change when you pass through me.
</section>
And here is the jQuery code:
var header = $('header'),
blueSection = $('section.blue'),
// Calculate when to change the color.
offset = blueSection.offset().top + blueSection.height() - header.height();
$(window).scroll(function(){
var scroll = $(window).scrollTop();
// Remove Class "dark" after scrolling over the dark section
if (scroll >= offset) {
header.removeClass('dark');
} else {
header.addClass('dark');
}
// Remove Class "no-shadows" whenever not on the top of the page.
if (scroll >= 1) {
header.removeClass('no-shadow');
} else {
header.addClass('no-shadow');
}
});
And for those of you who like to use jsfiddle(like me!):
https://jsfiddle.net/shock/wztdt077/6/
Thanks ahead guys!
Here is what I've come up with:
var header = $('header'),
blueSection = $('section.blue'),
// Calculate when to change the color.
offset = blueSection.offset().top + blueSection.height() - header.height();
var add = function(obj, cls) {obj.addClass(cls);}
var remove = function(obj, cls) {obj.removeClass(cls);}
var stylePoints = [offset, 1, 100, 200];
var styleTo = ['dark', 'no-shadow', 'blue', 'tall'];
var styleType = [add, add, remove, remove];
$(window).scroll(function() {
var scroll = $(window).scrollTop();
for (i = 0; i < stylePoints.length; i++) {
var func = styleType[i];
if (scroll >= stylePoints[i])
(styleType[i] == add) ? remove(header, styleTo[i]) : add(header, styleTo[i]);
else func(header, styleTo[i]);
}
});
It's not that much longer than your current jQuery, and allows for (theoretically) an infinite number of style changes without having to add a million long if/else statements. To add a new style change, you have to add a value to the end of each of the three arrays. stylePoints specifies the scrollTop() value at which a style should either be added or removed. styleTo specifies the class to be added or removed. styleType specifies whether this class should be added or removed when the user is scrolled above the corresponding stylePoints value. The opposite will occur when the user is scrolled below or at the corresponding stylePoints value. For instance, you can see from the code that the tall class will be removed from the header when the user is scrolled above 200, and added when the user is scrolled below or at 200.
How do I flow a text stream from one div to the next? Each div has a fixed height and width and I need the data to be passed to the first, then if that is filled overflow to another etc. (The second etc. divs need to be dynamically created). Eventually the divs will be contenteditable, this is the page technique for a simple WYSIWYG style editor.
Please help...
JS Fiddle (note zoom in use on body)(I need to reflow on keyup/down, make pages and remove as necessary and be able to add in the middle)
function loadgo(){
run();
var h = document.getElementById('page'+(document.getElementById("pagecount").value-1)).offsetHeight;
document.getElementById("loadgo").value = h+1;
if (h > 1135){
var pagecount = document.getElementById("pagecount").value;
//$('body').append("<div class=page style='color:#F00' id='page"+pagecount+"' contenteditable>"+this.id+"</div>");
var objTo = document.body;
var divtest = document.createElement("div");
divtest.style.color = '#F00';
divtest.id = "page"+pagecount;
divtest.className = 'page';
divtest.contentEditable = "true";
divtest.innerHTML = "new div";
objTo.appendChild(divtest);
document.getElementById("page"+pagecount).focus();
document.getElementById("pagecount").value++;
zoomin();zoomout();
run();
}
}
function run(){
setTimeout(function() {
loadgo();
}, 500);
}
loadgo();
What you're looking for is called CSS Regions. This allows your text to flow through various containers placed on your site.
You can read about it on Adobe's site, and Apple has a nice WWDC video explaining how to implement it (starts at 8:40). Also check out the Editor's Draft.
I´m developing a Javascript game and I have to place random coins in the HTML document. I have used this code so far:
createCoin() {
section=document.createElement("div");
section.innerHTML='<img src="./img/coin.png"/>';
document.body.appendChild(section);
}
This code simply places an image coin in the coordinates (0,0) of the document. What I want to do is access that recently created "div" and give it a random coordinate that I generate in another function so if I call several times the createCoin it creates several coins in the document. I can't use jQuery. Any ideas?
after create div element with id='coin' , to give the random position to div, use this:
<div id="coin" style="position:absolute">coin image</div>
<script language="javascript" type="text/javascript">
function newPos(){
var x=Math.random()*1000;
x=Math.round(x);
var y=Math.random()*500;
y=Math.round(y);
document.getElementById("coin").style.left=x+'px';
document.getElementById("coin").style.top=y+'px';
}
newPos();
</script>
we consider that createCoin() function execute once, on the onload() event. and then the newPos() function must be run.
Have createCoin return the div and then use it.
createCoin() {
section=document.createElement("div");
section.innerHTML='<img src="./img/coin.png"/>';
document.body.appendChild(section);
section.style.position = 'absolute';
section.style.left = '0px'; // units ('px') are unnecessary for 0 but added for clarification
section.style.top = '0px';
return section;
}
e.g.: var coin = createCoin(); coin.style.left = ???; coin.style.top = ???;
Can someone tell me how I can achieve the following?
I want to display a banner on my website's page (of course this is easy). However I want it to appear randomly (a single time) in one of the 4 positions I selected (DIV ID's bannerpos1, bannerpos2, bannerpos3 and bannerpos4).
If the banner shows up in bannerpos2, it shouldn't appear at any other location and vice versa.
And, only if possible, it should display a random banner as well (choice out of 3 banners or so).
So in short; I want a random banner in a random position on my page. Of course the banners and positions are yet to be defined.
Can someone help me, or point me in the right direction?
//update 7th of November
Okay, I have been fooling around with the script as show by Joe, however I am experiencing some problems...
Currently the code looks like this (before body-tage):
<script type="text/javascript">
$(function(){
var position = Math.floor((Math.random()*3));
console.log(position)
var $a = $("#advertentieplaats1");
var $b = $("#advertentieplaats2");
var $c = $("#advertentieplaats3");
var $advertentietype1 = $("#advinhoud1");
var $advertentietype2 = $("#advinhoud2");
var $advertentietype3 = $("#advinhoud3");
if (position == 0){
$a.append($advertentietype1);
}
if (position == 1){
$b.append($advertentietype2);
}
if (position == 2){
$c.append($advertentietype3);
}
});
</script>
And at the bottom of the page I have the following:
<div id="advinhoud1">adsense code 1</div>
<div id="advinhoud2">adsense code 2</div>
<div id="advinhoud3">adsense code 3</div>
Or there are some problems with this, or I am doing it wrong somehow...
In Firefox it shows the adsense code on random (defined) locations. It also shows the remaining 2 advertisements at the bottom (which should not be visible or even loaded).
In Internet Explorer it doesn't do anything at all...? All Adsense is shown at the bottom, nothing in random locations...?
Something like this. You can make it more dynamic, but here's the idea.
var position = Math.floor((Math.random()*3));
var $a = $("#myDiv1"); // Get the three containers as JQuery objects by id.
var $b = $("#myDiv1");
var $c = $("#myDiv1");
var $myAd = $("#myAd"); // Get the content you want to place.
// You could include it as a string in your JS
// or as a hidden element.
if (position == 0)
{
$a.append($myAd);
}
if (position == 1)
{
$b.append($myAd);
}
if (position == 2)
{
$c.append($myAd);
}