javascript - change image width? - javascript

I am using the following code to check if the width of an image is larger than 700. If that the case then I want to set it to 700
<img src="" id="main_image">
<script>
if(document.getElementById(main_image).width > 700) {
document.getElementById(main_image).width = 700;
}
</script>
after some search I found the above code but it is not working. Tell me what I am doing wrong ?

use "main_image" instead of main_image
<script>
if(document.getElementById("main_image").width > 700) {
document.getElementById("main_image").width = 700;
}
</script>
<img src="" id="main_image">
or you can use style also
document.getElementById("main_image").style.width = "700px";

Try with style:
window.onload = function() {
if(+(document.getElementById('main_image').style.width) > 700) {
document.getElementById('main_image').style.width = '700px';
}
};
If you have set width attribute then you would use getAttribute('width') and setAttribute(700) or directly width as you were doing. But if it comes from CSS, you will need to use style like shown above.

Your issue is probably because you are running the script before the element exists on the page. Try reversing the script and the img tag.

Related

Script Not Working on Website But Working on JsBin, Jsfiddle After One Refresh

This is a simple jquery script which finds a image greater than 300px and show url in paragraph. And this code working on online editor sites like jsbin but same code not working on website.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<main>
<p>
</p>
<img src="http://icons.iconarchive.com/icons/icons-land/metro-raster-sport/128/Soccer-Ball-icon.png">
<img src="http://www.iconarchive.com/download/i65352/icons-land/metro-raster-sport/American-Football-Ball.ico">
<img src="http://simpleicon.com/wp-content/uploads/football.png">
</main>
<script>
$(function() {
$('main img').each(function() {
$Height = 300;
if ($(this).height() > $Height) {
$image = $(this).attr('src');
$('p').text($image);
return false;
}
});
});
</script>
</body>
</html>
But if you change Only the greater-than sign to less-than sign in jquery if statement, then script will work on both website and online editor and showing image url everytime you refresh it.
How to make this script work to also display a image url which is greater than some pixels?
I found a way which makes it work also on website:
Running the script in
$(window).on("load",function(){
}
Your code works before images are loaded. You should give it a bit delay .
Try this;
$(function() {
setTimeout(function(){
$('main img').each(function() {
$Height = 300;
if ($(this).height() > $Height) {
$image=$(this).attr('src');
$('p').text($image);
return false;
}
});
},150);
});
The jQuery code executes as soon as the DOM is ready— it does not wait for the images to load! Therefore, none of the images have a height when the script searches for them.
When you refresh, the images are loaded instantly from the cache, in time for jQuery to catch them.
Take a look at this StackOverflow thread for an idea of how to trigger your function in response to each image's onload event!
e.g.,
$('main img').on('load', function(){
if ($(this).height() > 300)
$('p').text($(this).attr('src'))
;
});
Note that this code should supplement the code you've already written, since the jQuery documentation points out how the load event can fail to fire if the images are already in the cache.
calling .widht() or .height() also calculates padding assigned to the element.
try remove padding from the element, or you can simply subtracts the padding from the element
i.e;
remove padding:
main > img{padding: 0;}
Calculate the image height and remove padding:
$(function() {
$img = $('main img');
$img.each(function() {
var tp = parseInt($img.css('padding-top'), 10);
var bp = parseInt($img.css('padding-bottom'), 10);
$Height = 300;
if ($(this).height() - (tp + bp) > $Height ) {
$image=$(this).attr('src');
$('p').text($image);
return false;
}
});
});
Hope this will help. :)
just add https: before //ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js and then try.
note : your system must be connected to the internet or provide system file url for jquery.min.js
Javascript in both JSBin links are same,there is no differences.
If you want your function to work properly just add "$(document).ready" on your function like:-
$( document ).ready(function() {
$('main img').each(function() {
$Height = 300;
if ($(this).height() > $Height) {
$image=$(this).attr('src');
$('p').text($image);
return false;
}
});
});
Hope,this will for both web & JSBin.
Please read: -https://learn.jquery.com/using-jquery-core/document-ready/

Change the height of div using javascript

I want to change the height of div when I scroll
#H {
position: fixed;
height: 200px;
background: red;
width: 200px
}
<div style="height:2000px; position:relative">
<div id="H"></div>
</div>
<script type="text/javascript">
window.onscroll = function() {
myFunction()
};
function myFunction() {
VAR X = document.getElementById("H");
if (document.body.scrollTop > 0 || document.documentElement.scrollTop > 0) {
X.css("height": "100px");
} else {
X.css("height": "200px");
}
}
</script>
But the code is not working. In the above code I tried to change the height of the div with id="H" on scroll from 200, that I have mentioned in the CSS to 100, but the JS is not running.
You have some problem in JavaScript.
Change it to like:
<script>
window.onscroll = function() {myFunction()};
function myFunction() {
var X=document.getElementById("H");
if (document.body.scrollTop > 0 || document.documentElement.scrollTop > 0) {
X.style.height = "1000px";
}
else {
X.style.height = "200px";
}
}
</script>
VAR X should be var X
And
X.css("height":"1000px"); change style like X.style.height = "1000px";
Working Fiddle
there are a few javascript errors in your code.
VAR X=document...
"var" has to be lower case, not upper case.
X.css(...)
"css" is not a function. Use X.style.height instead.
Generally look into how to debug javascript code. A good browser is your friend with this (e.g. Firefox or Chrome). Use console.log("foo"); to print a message or a variable to the browsers console to see what happens in your code. You can also use step by step debugging.
If you use the JavaScript console in your browser, you can see that document.getElementById("H").css is not a function.
Instead use for example document.getElementById("H").style.height = "300px";
CSS is not directly accessible in JavaScript unless you use getComputedStyle API, however the class can be accessed using element.className and changed as long as you have the relevant class already created.
element.style.property is how you change inline styles. There is a big difference in both, in that one is part of the DOM structure while the other is connected to the DOM via a class name and the stylesheet.
Specific to you question:
Here is the fiddle
window.onscroll = function() {myFunction()}; is simply window.onscroll = myFunction it is the same and more idiomatic.

Change image source folder for mobile version with javascript

Sorry I'm a newbie with JS and I've been having trouble with some JS I found here on stackoverflow. My situation is that I have a div with two images inside, and I want to change the source path of those images when the window is less than 480px. My code is this:
<div id="bigFoto">
<img src="img/photo1.jpg" alt="text for alt" id="photo1">
<img src="img/photo2.jpg" alt="text for alt" id="photo2">
</div>
And The current script I'm running is:
$(window).resize(function(){
var width = $(window).width();
if (width < 481) {
$("#bigFoto img#photo1").attr("src","img/mobile/photo1.jpg");
$("#bigFoto img#photo2").attr("src","img/mobile/photo2.jpg");
}
else{
$("#bigFoto img#photo1").attr("src","img/photo1.jpg");
$("#bigFoto img#photo2").attr("src","img/photo2.jpg");
}
});
This script is working right, but now let's say I want that div to have 20 images, my guess is that I would have to add every one of them in this script right?
The real question: is there a way to target all images instead and just add the /mobile part on the source path? ,since the filename remains the same.
Thanks so much for your help!
You can use jQuery's each function to loop through all the elements returned by a query
$(window).resize(function(){
var width = $(window).width();
if (width < 481) {
$("#bigFoto img").each(function(index){
var src = $(this).attr("src")
var photoName = src.substr(src.lastIndexOf("/"));
$(this).attr("src", "img/mobile/"+photoName)
})
}
else{
$("#bigFoto img").each(function(index){
var src = $(this).attr("src")
var photoName = src.substr(src.lastIndexOf("/"));
$(this).attr("src", "img/"+photoName)
})
}
});

Get the iframe height from the javascript

I have a iframe tag embedded in the webpage similar to
<iframe id="xyz" height="900" width="800" src="www.pqr.com></iframe>
I'm trying to get the height and width of the iframe using:
function getDimensions()
{
var iframelist = document.getElementsByTagName("iframe");
for(var i=0;i<iframelist.length;i++)
{
if(iframelist[i].id == "xyz")
{
var width = iframelist[i].height;
var height = iframelist[i].width;
var src = iframelist[i].src;
}
}
}
i am getting 0 value for width and height but src is getting proper values.
I am inserting the above javascript function defination into the webpage using NPN_Evaluate() function and again calling the function using the NPN_evaluate.
Help me to fix this problem.
Can't you use something like this..
var iframelist = document.getElementById("xyz");
alert(iframelist.offsetHeight​);​
http://jsfiddle.net/dQjqR/
Or are you trying to access dimensions from within the iframe?
This seems to be working here on this demo, which browser are you testing it on?
DEMO

How can I resize the recaptcha in Greasemonkey?

I want to re size the text from the captcha to be easier to see, with Greasemonkey.
How can I do it?
For example, I have this captcha:
<div id="recaptcha_image" style="width: 300px; height: 57px; ">
<img style="display:block;" height="57" width="300" src="http://www.google.com/recaptcha/api/image?c=03AHJ_VuuqeICMpU36GlHCSchBzERwiDzTH4A1RHobtEpbbSK5lWC47EVkgeuF_ause8bnYTHGhjRr_GFiVMh9e4sZFXIBlv4-vcY7WXNjtBHhVmIl2Z5tqK_CY5hRZjtr-MWDUrBOr7mQE0ZqfU8XeeUeXLM5cxcwEQ">
</div>
I want to change the height="57" and the width="300" from the second line (from the image style) to 85 and 450 respectively.
Changing it into the inspect works correctly, but how can I do to do it always with Greasemonkey?
These userContent.css entries might work:
div#recaptcha_image,
div#recaptcha_image > img {
width: 450px !important;
height: 85px !important;
}
Since this is Greasemonkey, I'm going to assume you're using a reasonably up-to-date version of Firefox. In which case, you might be able to use querySelector:
var query = document.querySelector("#recaptcha_image > img");
if (query) {
query.style.width = "450px !important";
query.style.height = "85px !important";
}
If that doesn't work, you can try setting the img's attributes instead:
var query = document.querySelector("#recaptcha_image > img");
if (query) {
query.setAttribute("width", "450");
query.setAttribute("height", "85");
}
If that doesn't work, you can try setting both the box and the img:
var element = document.getElementById("recaptcha_image");
if (element) {
element.style.width = "450px !important";
element.style.height = "85px !important";
}
var query = element.querySelector("img");
if (query) {
query.setAttribute("width", "450");
query.setAttribute("height", "85");
}
Do:
var img = document.evaluate("//div[#id='recaptcha_image']/img", document, null, 9, null).singleNodeValue;
img.setAttribute('width', '85');
img.setAttribute('height', '450');
If the recaptcha is in an iframe, then #include the iframe's url, and not the parent's url, but note that this'll probably change the size of recaptcha's on every site, so you may want to check that window.top.location for window.top is the desired location.

Categories