I'm working on a responsive page whereby there's a embeded video content.
How can I update the parameter width/height in the iframe src as well as the iframe attribute width/height based on the width of the parent container as well as change when the window/orientation changes?
My mark-up:
<div class="content">
<div class="video">
<iframe src="http://www.foo.com/embeddedPlayer?id=4062930&width=672&height=377&autoPlay=false" width="672" height="377" border="0" frameborder="0" scrolling="no"></iframe>
</div>
</div>
Heres my JS:
var articleBodyWidth = $('.content').width(),
videoUrl = $('.video'),
videoSrc = videoUrl.find('iframe').attr('src'),
iframeWidth = videoUrl.find('iframe').attr('width'),
iframeHeight = videoUrl.find('iframe').attr('height');
// function to get param in url
function getParam(name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(videoSrc);
if(results == null) {
return "";
} else {
return results[1];
}
}
var newWidth = articleBodyWidth,
newHeight = Math.round( (iframeHeight / iframeWidth) * articleBodyWidth );
// update iframe width and height
videoUrl.find('iframe').attr({
width: newWidth,
height: newHeight
});
I think this should do
$('.video iframe').attr('src', 'http://www.foo.com/embeddedPlayer?id=4062930&width=' + newWidth+ ' &height=' + newHeight + ' &autoPlay=false').css({
width: newWidth,
height: newHeight
})
Another solution is to use regex to replace height and width in the src
function updateVideo() {
var src = $('.video iframe').attr('src');
src = src.replace(/&width=\d+&/, '&width=' + newWidth + '&');
src = src.replace(/&height=\d+&/, '&height=' + newHeight + '&');
$('.video iframe').attr('src', src).attr({
width: newWidth,
height: newHeight
});
}
$(window).on('resize', updateVideo)
What you'll have to do is control the size with CSS.
<iframe src="http://www.foo.com/embeddedPlayer?id=4062930&width=672&height=377&autoPlay=false" border="0" frameborder="0" scrolling="no" id="video"></iframe>
<style type="text/css">
#video { width:100%; height:auto: }
</style>
I stripped the width and height from <iframe> so CSS could take over.
#kcdwayne is right. You should put the CSS in control in a responsive page.
For an embedded video the only variable is "height", but if you use #media-queries you can set height for different screen sizes, depending on layout changes.
Here's how I would try doing it:
http://tinyurl.com/a2cxfe6
More info about embedded flash object here:
http://www.aleosoft.com/flashtutorial_autofit.html
Related
I have a project which consists of a HTML, JS and CSS file.
When I open the project in my browser I have an input field (url input), a button and a canvas.
After I insert the URL of an image in the input field and click the button, I want the canvas to resize according to the width and height of the image. Of course, I also want the image to be displayed in the canvas.
Note: Later I want to add a functionality where someone can resize the image with a slider. This means that I really have to save the width of the image in a variable.
So, my main problem is that I don't know how to get the width of that image.
The last thing I tried is the following:
$('#btn_load').click(function () {
input_url = $('#input_url');
var url = input_url.val();
var img_width = url.width;
...
});
Would be glad about some help here, since I tried a lot of stuff in the last hours :)
EDIT:
I now also tried the following:
var inputURL, imgWidth;
inputURL = $('#input_url');
$('#btn_load').click(function () {
var url = inputURL.val();
var img = new Image();
img.src = url;
img.onload = function () {
imgWidth = img.width;
};
canvas.css({
'background-image': 'url(' + url + ')',
//'background-size': 'cover',
});
//This is just to check the width value
inputURL.val(imgWidth + url);
});
But still doesn't work.
This will get the img width and height in the global variables 'imgHeight' and 'imgWidth' It will also display the image on the screen, width a slider to make it bigger or smaller,
the min and max value of the input type range are dynamically set to the original width and height divider by 2 or for the maximum multiplied by 2.
Javascript:
var imgHeight;
var imgWidth;
var img = new Image();
function LoadImage() {
input_url = $('#input_url');
img.src = input_url.val();
//img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
img.onload = function() {
imgHeight = this.height;
imgWidth = this.width;
//alert(imgHeight + " : " + imgWidth);
//Now set the image to html
document.getElementById("imgID").src=img.src;
//Now set the dimensions.
$("#imgID").css({'height' : imgHeight+'px', 'width' : imgWidth+'px'});
//Now set the range min to imgwidth / 2. and the max to imgwidth * 2
document.getElementById("range").min = imgWidth / 2;
document.getElementById("range").max = imgWidth * 2;
document.getElementById("range").value = imgWidth;
}
}
function ChangeImageSize(value) {
//Calculate new height so the image doesn't get stretched.
newHeight = value / imgWidth * imgHeight;
//Set the new width and height
$("#imgID").css({'height' : newHeight+'px', 'width' : value+'px'});
}
HTML
<button onclick="LoadImage()">click me</button>
<input type="range" id="range" oninput="ChangeImageSize(this.value)">
<input type="text" id="input_url">
<img id="imgID">
<html>
<head>
<script src="https://code.jquery.com/jquery-3.5.1.js" > </script>
<script>
function loadUrl() {
//You can get the value of your url_input and use it instead.
var url = "https://cdn.sstatic.net/Sites/stackoverflow/Img/apple-touch-icon.png?v=c78bd457575a"; //You can take it from your input_url
$("#img-size").attr("src", url);
};
function imageLoaded(sender){
alert($(sender).width() + 'x' + $(sender).height());
}
</script>
</head>
<body>
<img src="" id="img-size" onload="imageLoaded(this);">
<input type="button" onclick="loadUrl();" id="btn_load" value="Load" />
</body>
</html>
You should load the imag to get its natural width and height :
var img = new Image();
img.src = $('#input_url').val();
img.onload = function () {
imageWidth= img.naturalWidth;
imageHeight = img.naturalHeight;
...
}
I try to move the image in every click but it just move one time.See the code:
<img id="myImg" src="">
<script>
function move() {
var img = document.getElementById("myImg")
img.style.left += "2px";
}
</script>
<button onclick="move()"></button>
Anyone knows how to make it work?
When you get the value of left property, it looks like this: 0px. It's a string. So if you want to calculate it, you need to parse it to a number. Before doing that, you can split px part to get the number.
img {
position: absolute;
width: 150px;
height: 100px;
left: 0px;
}
button {
margin-top: 100px;
}
<img id = "myImg" src = "https://images.unsplash.com/photo-1474511320723-9a56873867b5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80">
<script>
function move(){
var img = document.getElementById("myImg");
img.style.left = +img.style.left.substring(0, img.style.left.length - 2) + 2 + 'px';
}
</script>
<button onclick = "move()">Move</button>
This line
img.style.left += "2px";
produces invalid CSS. You want to extract the integer each time, add 2, then add the "px" unit back in.
const img = document.getElementById("myImg")
function move() {
img.style.marginLeft = img.style.marginLeft ? parseInt(img.style.marginLeft, 10) + 2 + "px" : "2px"
}
<img id="myImg" src="https://placekitten.com/200/200">
<button onclick="move()">Move Image</button>
This is a very clumsy way to move an image. Please educate yourself about canvas object. But as you are a begginer and may just need a quick fix, here's a way to get your code working:
<img id = "myImg" style="width: 100px; height: 100px;" src ="https://upload.wikimedia.org/wikipedia/en/thumb/e/ec/Soccer_ball.svg/600px-Soccer_ball.svg.png">
<script>
var margin = 0;
function move(){
var img = document.getElementById("myImg")
margin += 2;
img.style.marginLeft = margin + "px";
}
</script>
<button onclick = "move()" >Move</button>
if you want to move image then you could move it either right or left for that try to fix your code at left - px
<img id = "myImg" src = "">
<script>
function move(){
var img = document.getElementById("myImg")
img.style.left += "2px";
}
function moveleft() {
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
}
</script>
<button onclick = "moveleft();">
Can anyone help me to get the image details in jQuery. Have dome with W X H, also want to add date too - realWidth, realHeight, 'Date'.
$(document).ready(function() {
var img = $("#img1");
// Create dummy image to get real size
$("<img>").attr("src", $(img).attr("src")).load(function() {
var realWidth = this.width;
var realHeight = this.height;
$('#resolution').html(realWidth + " X " + realHeight);
});
});
The issue is because load() is use to make an AJAX request to retrieve HTML content. To hook to the load event, use on() instead. Try this:
$(document).ready(function() {
var $img = $("#img1");
$("<img />").prop("src", $img.prop("src")).on('load', function() {
var realWidth = this.width;
var realHeight = this.height;
$('#resolution').html(realWidth + " X " + realHeight);
});
});
img {
width: 50px;
height: 37px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://i.imgur.com/3xi2iIl.jpg" id="img1" />
<div id="resolution"></div>
Also, I can only assume you need to retrieve the image size in this manner as the image is displayed in altered dimensions in the DOM. If this is not the case, you can read the size from #img1 directly.
I created a named function that gets 2 params. First param is an image filename (str) without his expression. Second param is image height (num) in pixels.
I want to display image with given height within html document.
eg:
<div><script>showImage('test', 100);</script></div>
I believe that function is not called the right way.. How to correctly call the function to display images inside any div.
function showImage (imgfilename, imgheight) {
var img = '';
imgheight = typeof(imgheight) !== "undefined" ? imgheight : "64";
imgheight = 64 + (imgheight - 64);
img += '<img src="https://i.imgsafe.org/'+imgfilename+'.png" width="64px" height="'+imgheight+'px">';
//console.log (img);
return img;
}
body {background-color: #ccc;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="img1"><script>showImage('7a622f4233', 68);</script></div>
<div id="img2"><script>showImage('7a622f4233', 80);</script></div>
<div id="img3"><script>showImage('7a5fa34d31', 60);</script></div>
Try the following:
Use data attributes to store your info
<div class="img" data-id="7a622f4233" data-height="68"></div>
<div class="img" data-id="7a622f4233" data-height="80"></div>
<div class="img" data-id="7a5fa34d31" data-height="60"></div>
js:
$('.img').each(function(){
var imgheight =$(this).attr('data-height');
var imgfilename = $(this).attr('data-id');
imgheight = imgheight != "" ? imgheight : "64";
var img = '<img src="https://i.imgsafe.org/'+imgfilename+'.png" width="64px" height="'+imgheight+'px">';
$(this).html(img);
})
You are returning a string, but you should add the img to the DOM, as
function showImage (imgfilename, imgheight, elementId) {
var img = '';
imgheight = typeof(imgheight) !== "undefined" ? imgheight : "64";
imgheight = 64 + (imgheight - 64);
img += '<img src="https://i.imgsafe.org/'+imgfilename+'.png" width="64px" height="'+imgheight+'px">';
//console.log (img);
$("#" + elementId).append(img);
}
And calling the method with:
<div id="img1"><script>showImage('7a622f4233', 68, 'img1');</script></div>
Edit: the solution of madalin ivascu is also a very good one, however it is a different approach.
<div id="img1"><script>document.write(showImage('7a622f4233', 68));</script></div>
You need to write your returned img tag out.
You need to do a lot of reading. That's no way to call a function and to return an html element within a script tag?
First off, correct your function to append the generated html into another element:
function showImage (imgfilename, imgheight, imgId) {
var img = '';
imgheight = typeof(imgheight) !== "undefined" ? imgheight : "64";
imgheight = 64 + (imgheight - 64);
img += '<img src="https://i.imgsafe.org/'+imgfilename+'.png" width="64px" height="'+imgheight+'px">';
//console.log (img);
document.getElementById(imgId).innerHTML = img;
}
Then call it like this:
showImage('name', height, 'imgId');
And please remove the script tags from the divs:
<div id="img1"></div>
I am using this script to display an image preview for users when they register to my site. I have it set to be on the client side. Other-words, the image isn't uploaded for the preview.
Trying to auto resize the image the user selects to maintain it's apect ratio when it is display back on the page. Max size 150x150.
<script type='text/javascript'>
function userImage(file) {
if(document.all)
document.getElementById('showImage').src = file.value;
else
document.getElementById('showImage').src = file.files.item(0).getAsDataURL();
if(document.getElementById('showImage').src.length > 0)
document.getElementById('showImage').style.display = 'block';
}
</script>
<input type='file' name='avatar' onchange='userImage(this);' />
<img id='showImage' style='display:none;' />
Changed the suggestion to a simpler model. Please note that IE may need your site to be in trusted zone to allow it to show the image
<script type='text/javascript'>
function userImage(file) {
var img = document.getElementById("img1");
img.onload=function() { this.parentNode.style.display="" }
img.src=(file.files)?file.files.item(0).getAsDataURL():file.value;
}
</script>
<input type="file" name="avatar" onchange="userImage(this);" />
<div id="showImage" style="display:none" ><img name="img1" id="img1" src="dummy.gif" width="150" /></div>
If you are/can use JQuery. Check this for Getting Proportional width where you pass expected height and calculate proportional width.
function GetWidth(expectedHeight )
{
var width = $("#showImage").width();
var height = $("#showImage").height();
var targetWidth = Math.round(expectedHeight * width / height);
$("#showImage").attr("width", targetWidth );
$("#showImage").attr("width", expectedHeight );
}
with javascript
function GetWidth(expectedHeight )
{
var img = document.createElement("img");
var width = img.width;
var height = img.height;
var targetWidth = Math.round(expectedHeight * width / height);
img.width=targetWidth ;
img.height = expectedHeight ;
}