Toggle iframe height/width - javascript

So I would like to make a toggle button for 2 different sizes of my frame.
I was able to make 2 simple buttons for resizing the iframe with these simple functions
function changeframe_big()
{
document.getElementById('frame').width = 1000;
document.getElementById('frame').height = 600;
}
function changeframe_small()
{
document.getElementById('frame').width = 640;
document.getElementById('frame').height = 360;
}
(Please ignore the ratios, I'm just testing it.)
And the buttons ...
<button id="change_big" onClick="changeframe_big()">BIG</button>
<button id="change_small" onClick="changeframe_small()">SMALL</button>
So, and basically I would like to make only one button, which would toggle between these two sizes.
I'm somehow struggling to get this done.
I appreciate any help.
Thank you.

assuming that your given code works, you could do the following:
your HTML:
<button id="toggle" onClick="toggle()">Toggle</button>
your JS:
var small=false;
function toggle()
{
if(small){
document.getElementById('frame').width = 1000;
document.getElementById('frame').height = 600;
small=false;
}
else{
document.getElementById('frame').width = 640;
document.getElementById('frame').height = 360;
small=true;
}
}
basically what this code does is it checks if "#frame" is small or big (assumed that the default size is big), and then toggles it to the other size.

Related

CSS attribute not always being grabbed by javascript correctly

I am trying to resize the side bars whenever the image changes.
I have my javascript trying grab the height of the image after it changes
var imgHeight = $('#mainImg').height();
var currImg = 0;
var imagesSet = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg", "6.jpg"];
var imageLoc = "images/zalman/"
$('#bttnRight').click(function(){
nextImg();
imgHeight = $('#mainImg').height();
resizeBttn();
});
function nextImg(){
currImg++;
if(currImg>=imagesSet.length){
currImg=0;
}
$('#mainImg').attr("src",imageLoc + imagesSet[currImg]);
}
function resizeBttn() {
$(document).ready(function() {
$('#bttnLeft').css("height",imgHeight);
$('#bttnLeft').css("bottom",imgHeight/2-5);
});
$(document).ready(function() {
$('#bttnRight').css("height",imgHeight);
$('#bttnRight').css("bottom",imgHeight/2-5);
});
}
for some reason, it doesn't always grab the height at the correct time and the side bars will stay at the previous height.
Below I have a JSFiddle that should be working the way my setup is.
Please excuse any inconsistencies and inefficiencies, I am learning.
Just seems weird that it would sometimes grab the height and sometimes not.
I will also be attaching an image of what I see sometimes from the JSfiddle.
I will also attach an image of what I see on my site I am actually writing.
https://jsfiddle.net/6bewkuo5/6/
The issue is because your JavaScript accessing the height of the image before the image as actually been re-rendered in the DOM. Adding a slight delay after assigning the new image source may help things, but...
You actually don't need to use JavaScript to set the height of the buttons
You can achieve what you're after by placing the buttons and image inside of a container with css attribute display: flex.
Like this:
.container {
display: flex;
justify-content: center;
}
<div class="container">
<button class="prev"><</button>
<img src="https://www.avalonwinery.com/wp-content/uploads/2013/12/200x300.gif">
<button class="next">></button>
</div>
Elements within a flex container will automatically fill the height, this includes buttons. Because the images will automatically adjust the height of the container, the buttons will also automatically adjust their height to match.
Run the example below
const images = [
"https://www.avalonwinery.com/wp-content/uploads/2013/12/200x300.gif",
"https://images.sftcdn.net/images/t_app-logo-xl,f_auto/p/ce2ece60-9b32-11e6-95ab-00163ed833e7/1578981868/the-test-fun-for-friends-logo.png",
"https://hiveconnect.co.za/wp-content/uploads/2018/05/800x600.png",
"https://upload.wikimedia.org/wikipedia/commons/b/b5/800x600_Wallpaper_Blue_Sky.png"
]
const imageEl = document.querySelector('img')
let imageIndex = 0
document.querySelector('.prev').addEventListener('click', e => {
if (--imageIndex < 0) { imageIndex = images.length - 1 }
imageEl.src = images[imageIndex]
})
document.querySelector('.next').addEventListener('click', e => {
if (++imageIndex > images.length - 1) { imageIndex = 0 }
imageEl.src = images[imageIndex]
})
body {
background-color: #206a5d;
color: #ffffff;
text-align: center;
}
.container {
display: flex;
justify-content: center;
}
img {
max-width: 50%;
}
<h1>Zalman Build</h1>
<div class="container">
<button class="prev"><</button>
<img src="https://www.avalonwinery.com/wp-content/uploads/2013/12/200x300.gif">
<button class="next">></button>
</div>
The reason is because the resizeBttn code is firing before the image has actually finished downloading and loading into the DOM. I made these changes in your fiddle:
var imgHeight = $('#mainImg').height();
var currImg = 0;
var imagesSet = ["https://www.avalonwinery.com/wp-content/uploads/2013/12/200x300.gif","https://images.sftcdn.net/images/t_app-logo-xl,f_auto/p/ce2ece60-9b32-11e6-95ab-00163ed833e7/1578981868/the-test-fun-for-friends-logo.png", "https://hiveconnect.co.za/wp-content/uploads/2018/05/800x600.png", "https://upload.wikimedia.org/wikipedia/commons/b/b5/800x600_Wallpaper_Blue_Sky.png"];
var imageLoc = "images/zalman/"
$(document).ready(function() {
resizeBttn();
});
$( window ).resize(function() {
/* imgHeight = $('#mainImg').height() */; // commented out; we do this in resizeBttn now
resizeBttn();
});
$('#bttnLeft').click(function(){
prevImg();
/* imgHeight = $('#mainImg').height() */; // commented out; we do this in resizeBttn now
/* resizeBttn() */; // we do this as an `onload` to the image now
});
$('#bttnRight').click(function(){
nextImg();
/* imgHeight = $('#mainImg').height() */; // commented out; we do this in resizeBttn now
/* resizeBttn() */; // we do this as an `onload` to the image now
});
function nextImg(){
currImg++;
if(currImg>=imagesSet.length){
currImg=0;
}
$('#mainImg').attr("src",imagesSet[currImg]);
}
function prevImg(){
currImg--;
if(currImg<0){
currImg=imagesSet.length-1;
}
$('#mainImg').attr("src",imagesSet[currImg]);
}
function resizeBttn() {
imgHeight = $('#mainImg').height()
// removed superfluous doc.ready
$('#bttnLeft').css("height",imgHeight);
$('#bttnLeft').css("bottom",imgHeight/2-5);
$('#bttnRight').css("height",imgHeight);
$('#bttnRight').css("bottom",imgHeight/2-5);
}
And then rewrote your <img /> tag to call resizeBttn on onload:
<img id="mainImg" src="https://www.avalonwinery.com/wp-content/uploads/2013/12/200x300.gif" onload="resizeBttn()"/>
You can see this in action in this fiddle.
Also, a few additional notes on your code, at a glance:
You have some invalid HTML; you're going to want to run that through an HTML validator and fix it, because sometimes it is fine, but sometimes it can lead to all sorts of strange behavior.
You're playing fast and l0ose with global variables in your JS that get set in different functions; it might work OK while the script is small, but as things scale it can quickly become difficult to maintain
You should really avoid abusing the onclick to get link-like behavior from <li> elements; it can impact SEO as well as accessibility. I'd recommend simply using an anchor element inside or outside the <li>
I'd recommend taking a close look at this answer by user camaulay; he makes an excellent point that this may not require JS at all- if a more elegant solution exists w/ CSS it is probably going to be more performant and maintainable.

Can you set the size of an element using getBoundingClientRect

I have a button that gets resized on the mouse enter event. I am wondering if its possible to resize it based on its height received from getBoundingClientRect().height.
This is what I've tried so far with variations of this but nothing seems to work
btn.onmouseover = function(){
let h = this.getBoundingClientRect().height;
this.style.width = "100%";
if(h != this.getBoundingClientRect().height)
{
this.getBoundingClientRect().height = h;
}
this.style.right = "4%";
}
What happens is the button resizes when the mouse is over the button due to the text inside of it being moved from two lines to one so I was wondering if there is a function call similar to getBoundingClientRect() where i can set the height of the button based on the height I get from h. This way the text inside the button being moved from 2 lines to one doesn't resize the whole button on mouseover.
Also setting the height from h to the style height of the button creates a weird offset so that's not really a viable solution for me in this scenario
I'm confused by this code. You are checking if the height you just obtained from getBoundingClientRect is equal to the height from getBoundingClientRect, and of course it will always be. And no, you can't possibly change the size of something by updating the information in the size you got from calling getBoundingClientRect. Anyway, if you really want to do something in JS relating to hovering, you need to use mouseenter and mouseleave, not mouseover.
But actually, you should be able to do this entirely in CSS.
button { width: 200px; height: 3em; }
button:hover { width: 400px; }
<button>Hi, I'm a button with some pretty long text</button>
If you really want to handle the mouse events yourself, then
const button = document.querySelector('button');
button.addEventListener('mouseenter', () => {
button.style.height = button.offsetHeight + 'px';
button.style.width = '600px';
});
button.addEventListener('mouseleave', () => {
button.style.width = button.style.height = '';
});
button { width: 240px; }
<button>Button with some pretty long text which will wrap</button>

Change image in html keeping size javascript

I am experimenting an issue while changing an image in a img tag of html.
I did an example in fiddle which works as my webpage with images I found on internet so they are not equal:
http://jsfiddle.net/kZp7V/
This is the script code:
var counterImage = 0;
var ccI = new Array('http://tiendas.fnac.es/la-canada/files/2010/12/Peque%C3%B1a-orquesta-mediterr%C3%A1neo-300x286.jpg',
'http://muack.es/wp-content/uploads/2013/04/smalldata1.jpg',
'https://pbs.twimg.com/profile_images/604644048/sign051.gif'
);
window.image = function(element){
if(counterImage < 3){
document.getElementById("EJ_test").setAttribute('src', ccI[counterImage]);
counterImage++;
}
else{
document.getElementById("EJ_test").setAttribute('src', ccI[0]);
counterImage = 1;
}
}
I want that all images to have the same aspect of the first one, I mean, same hight and width. Is is possible?
I was asked to do it with photoswipe but I find it a little bit difficult so I want to do this now and then, read carefully everything about photoswipe for next week.
EDIT: I changed the class="cropTest" to the div instead of the image and now all images are "resized". I use "" because they are smaller. The img tag adjust to the image but I don't want this happends. I want to have a diferent image but keeping the size. I don't mind the image looks blur or pixelated.
you can use getComputedStyle to get the current size of the image, and use that information once, for example by checking if the width style has already been set by you. Example:
window.image = function(element){
if (!document.getElementById("EJ_test").style.width) {
var currentStyle = window.getComputedStyle(document.getElementById("EJ_test"));
document.getElementById("EJ_test").style.width =
currentStyle.width;
document.getElementById("EJ_test").style.height =
currentStyle.height;
}
if(counterImage < 3){
document.getElementById("EJ_test").setAttribute('src', ccI[counterImage]);
counterImage++;
}
else{
document.getElementById("EJ_test").setAttribute('src', ccI[0]);
counterImage = 1;
}
}

How to make a Div's height change slower

I want to make a Div appear by scrolling down on a button click slowly from the top of the page. But when I do it with what I have now, it just appears very fast and does not really slide down. What am I doing wrong?
function showstuff(inquiryForm){
document.getElementById(inquiryForm).style.visibility="visible";
for (var i=0;i<300;i++)
{
document.getElementById(inquiryForm).style.height= i + "px";
}
}
You are looping 300 items and you try to find the element with getELementById and then trying to style the selected item
I think that makes the process really slow and laggy.
Here is an example that should help you understand the event loop,
and the use of setTimeout.
<div id="myDiv" style="width:10px;height:50px;background:#f00;"></div>
<button class="btn" onclick="start();">Start</button>
<button class="btn" onclick="stop();">Stop</button>
<button class="btn" onclick="reset();">Reset<button>
var timeout;
function start() {
var div = document.getElementById("myDiv");
var size = 10;
var func = function () {
timeout = setTimeout(func, 0);
div.style.width = size + "px";
if (size++ == 600) stop();
}
func(); // starts the process
}
function stop() {
clearInterval(timeout);
}
function reset() {
var div = document.getElementById("myDiv");
div.style.width = "10px";
}
this sort of thing is often handled using jquery, as it includes various animation functions, including a convenient short form that would be useful here:
once you've included the jquery library, you can use a function like this:
$(inquiryForm).slideDown( 500 );
where the argument is duration of the effect in ms
like so:
function showstuff(inquiryForm){
$(inquiryForm).slideDown( 500 );
}

A jQuery/javascript auto-sizable grid control

I am implementing a jquery file upload page. While a user is adding files, I want them to be getting listed in a form of an icons in an auto-sizable grid.
Auto-sizable means it provides maximum space for containing elements. When there is two objects - it woud look like (I know i will have to handle image resizing myself):
When several are added:
Is there a "grid control" (jquery perhaps) that does at least close to what I need sizing wise?
First of all, please keep in mind that I'm a jQuery newbie and this is my first post on Stackoverflow :)
I've the same problem and I've try to fix it using jQuery and CSS. This is my body tag content:
<div id="controls">
Controls:
<button id="add">+</button>
<button id="del">-</button>
Current ratio:
<span id="value"></span>
<button id="increase">+</button>
<button id="decrease">-</button>
Referred to:
<form style="display: inline;">
width<input type="radio" name="maximize" value="width">
height<input type="radio" name="maximize" value="height">
</form>
</div>
<div id="elements" style="width: 500px; height: 300px; background: black;">
</div>
<script>
ratio = 1;
ratioWidth = true;
function autoresize() {
boxes = $('#elements').children().size();
rows = Math.ceil(Math.sqrt(boxes/ratio));
columns = Math.ceil(boxes/rows);
if (!ratioWidth) {
tmp = rows;
rows = columns;
columns = tmp;
}
$('#elements').children().css('width', 100/rows+'%');
$('#elements').children().css('height', 100/columns+'%');
}
function add() {
red = Math.floor(Math.random()*256);
green = Math.floor(Math.random()*256);
blue = Math.floor(Math.random()*256);
color = 'rgb('+red+','+green+','+blue+')';
$('#elements').append("<div style=\"background: "+color+"; float: left;\"></div>");
autoresize();
}
function update() {
$('#value').text(ratio);
autoresize();
}
function remove() {
$('#elements').children().last().remove();
update();
}
function increase() {
ratio++;
update();
}
function decrease() {
if (ratio > 1) {
ratio--;
update();
}
}
$(document).ready(function() {
$('#add').click(add);
$('#del').click(remove);
$('#increase').click(increase);
$('#decrease').click(decrease);
if (ratioWidth) value = 'width'
else value = 'height'
$('input[type=radio]').filter('[value='+value+']').attr('checked', true);
$('input[type=radio]').live('change', function() {
if ($(this).val() == 'width') ratioWidth = true
else ratioWidth = false;
autoresize();
});
update();
//$(window).bind("resize", autoresize);
});
</script>
You could remove the background color stuff and put your icons centered in those boxes.
If you find a better way of if you improve this code, please let me know :)
Edit 1 - I've added some Math.floor(...) to remove a bug when boxes side has repeating decilmals: very size is a simple integer. Now dimensions are fetched from the container div, I use black as background color for the main container and I've noticed a little issue: sometimes I see a black border near the little boxes, even if I don't set any background color. Could it be a Firefox rendering glitch?
Edit 2 - Now it's possible to set if you prefer to auto-expand horizontally, vertically, or none of them. I've tried to write a better code, and I've commented autoresize when the window is resized (use it only if your container box hasn't a fixed height/width). I think that now it needs an ratio option, in order to specify if width have to be twice longer for example. Live example: http://experimental.frafra.eu/maxarea2.html
Edit 3 - New code! Better graphical representation and a new parameter: ratio. Ratio is a coefficient between the ratio between main container width/height and the elements one. Live example: http://experimental.frafra.eu/maxarea3.html

Categories

Resources