Having problems with grabbing image dimensions with jQuery - asp.net

I'm having a hard time picking up how to grab the dimensions of an element with jQuery. Here is my sample code:
$(document).ready(function() {
var width = $("#image_1").width();
var height = $("#image_1").height();
document.write(width);
document.write(height);
});
Now of course I have an image with an id of #image_1. What happens when I try to run it is that it outputs two zeros. Not null twice, or undefined twice.
Thanks for the help from a javascript newb.

Even though you've already chosen an answer, I am typing this one so you understand why your prior code did not work.
jQuery's document.ready function fires before images are loaded. Use window.load instead...
$(window).load(function() {
var width = $("#image_1").width();
var height = $("#image_1").height();
document.write(width);
document.write(height);
});
For what it's worth, I think it is better to use jQuery for this task because of the inherent cross-browser functionality.

Perhaps this was a typo in your question, but is the ID of your image really "#image_1"? For your code to work, it should be just "image_1". The "#" is only used in the jquery selector to specify that the text following it is an ID.

You may get 0 for the width and height if the image is not visible. (That's what just happened to me.)
Updated: You can confirm that the image is added to the DOM by checking the length property of the jQuery object:
var inDOM = ($('#image_1').length > 0);

This works for me:
<head>
<script type="text/javascript">
function foo() {
var image = document.getElementById("the_image");
alert(image.offsetWidth);
alert(image.offsetHeight);
}
</script>
</head>
<body onload="foo();">
<img src="img.png" id="the_image">
</body>
This works as long as the image is not set to display: none; Using offsetWidth and offsetHeight also has the advantage of not requiring jQuery, at all.

Related

if image width > 400 = image width = 100% css

I'd like to check if an image width has more than 400px I'd like this image to get full div width. if image is less than 400px just print it in its normal size.
any ideas how to do this?
<div id="volta">
<img src="/img/volta.jpg">
</div>
#volta{
width:500px;
}
As far as I know, this does not exist in CSS. What you should do instead is use classes.
Define some CSS class that applies the styles you want:
.long_width {
background: blue;
}
Then you would use Javascript to check the width of the image. You don't need jQuery to do this you can do it in vanilla Javascript (unless you already have jQuery imported and need it for other things). Maybe something like this:
let elm = document.querySelector('[src="/img/volta.jpg]"');
let width = window.getComputedStyle(elm).getPropertyValue('width');
And then you would use Javascript to add and remove styles accordingly:
if (width > 400) {
elm.classList.add("long_width");
}
else {
elm.classList.remove("long_width");
}
The specific answer to your question depends on what your intentions are. But to keep your code simple, you should use Javascript to handle the logic and not depend on CSS selectors for things this complicated. Instead, create a CSS class that contains the styles you need, and then use Javascript to apply it based on the size of the user uploaded image.
Additionally, if the user uploads the image, you should load it into memory and check its attributes in memory rather than by depending on a DOM element. Something like:
let img = new Image();
img.src = "{data URL of img}"
You will need javascript / jQuery to work. Something like this:
$('img').each(function(){
if($(this).width() > 400){
$(this).css('width', '100%');
}
});
Here is also working jquery example.
Apply an id to the image, and with jquery check its width
If it is greather than 400px modify his width or add a class that does the same.
Example
$(document).ready(function(){
if($("#image").width() > 400){
$("#image").css("width", "100%");
}
else{
$("#image").css("width", "10px");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id = "image" src = "https://pm1.narvii.com/6919/98f453834b5d87a6c92118da9c24fe98e1784f6ar1-637-358v2_hq.jpg"/>
You can do it like FlokiTheFisherman (with %), or you can use "wv" instead of "%".
I recommend using vw.
img[width='400'] {
width: 100%;
}

Hovering over an image changes HTML background

Basically:
div:hover
{
body{ background-image:(bg.png); }
}
This is logical code, I know it does not work, but its the best how I can show you my problem.
Well what your trying to accomplish cannot be achieved that way using Css only, You can do it using jquery like this
$("#someDiv").hover(function(){
$("body").css("background-image", "url('image_url')")
});
In css ,You can not do this as "body" is parent element to "div" and it should come next to the element hovered to use the for format like
firstelement:hover second_element {/*styles*/}
you can use jquery to achieve it
$("div").hover(function(){
$("body").css("background", "url('url_of_image_here')")
});
or javascript
elem = document.getElementById("ID");
elem.addEventListener("mouseout", function(){
document.getElementsByTagName("body")[0].style.backgroundImage="url()";
});

CSS3: set background image to rel attribute value

I'm looking to set the background-image (or even render an image via the pseudo elements :after or :before) to the value, which will be a URL, of a rel attribute, but only in certain cases (this is a cloud file listing). For example:
HTML:
<div class="icon ${fileExtension}" rel="${fileURL}"></div>
It would be great if I could do something like this:
CSS:
.icon.png,
.icon.jpg,
.icon.jpeg,
.icon.bmp,
.icon.gif { background-image: attr(rel,url); }
... but obviously that doesn't work as, if I'm not mistaken, the attr() CSS function only works inside pseudo element blocks.
I know there are ways of doing this using conditional JSP or even jQuery logic, but I'd like to figure out a neat way of doing it via CSS3, since I'm only concerned with modern browsers at the moment anyway.
Also, I don't want to explicitly set the background image to the URL or create an <img> element, because by default if the file is not a supported image, I'd rather display a predetermined set of icons.
Using
.icon:after{ content: ""attr(rel)""; }
displays the rel value as text.
A jQuery solution is to add the background-image (taken from the rel value) as inline CSS:
jQuery(function($) {
$('.icon').each(function() {
var $this = $(this);
$this.css('background-image', 'url(' + $this.attr('rel') + ')');
});
});
I've tried to do something using jQuery but i don't exactly understand what you want so i can't go on with my code. So far i've done only this.
EDITED I hope it's exactly what you need
$(function(){
var terms = new Array('png','jpg','jpeg','bmp','gif');
$('.icon').each(function(){
var t = $(this),
rel = t.attr('rel'),
cls = t.attr('class');
cls = cls.split(' ');
for (var i=0; i < terms.length; i++) {
if (terms[i] == cls[1]) {
t.css('background-image','url('+rel+')');
}
}
});
});
if you can give me a better example, to undestand exactly what you want, i hope somebody from here will be able to solve your problem.
Regards,
Stefan
I've decided to go the jQuery route, and used a combination of #ryanve and #stefanz answers. Thanks guys
$(document).ready(function() {
$(".png,.jpg,.jpeg,.bmp,.gif,.tiff").each(function(n) {
var bg = 'url(' + $(this).attr("rel") + ')';
$(this).css('background-image', bg);
});
});
I think this is relatively neat/concise and works well for my needs. Feel free to comment on efficiency, methodology, etc.

IE select issue with hover

A friend and myself are trying to workaround IE (7/8). We have built a canonical example here:
http://www.mathgladiator.com/share/ie-select-bug-hover-css-menus.htm
Using a CSS menu, we would like to have selects in them. However, in IE, the menu goes away when you interact with the select box. We believe this has to do with a bug in how selects affect events.
Is there a workaround? At least with pure CSS or DOM hacks?
I do not think there is a pure CSS way around this. This is due to a very common bug to the way IE handles events on select elements.
You can however work around it with Javascript:
<script type="text/javascript">
$(document).ready(function () {
$('.nav_element a').mouseover(function() {
$('.submenu').hide();
$(this).parent().find('.submenu').show();
});
$('.submenu').mouseover(function() {
$(this).show();
});
$('.submenu').mouseout(function (e) {
// Do not close if going over to a select element
if (e.target.tagName.toLowerCase() == 'select') return;
$(this).hide();
});
});
</script>
The code above uses jQuery.
Here is a way to improver select behavior in IE7/8, but it does not fix the issue
Change DOCTYPE
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
Add script
<script>
function ddlOut(e) {
setTimeout(function() { e.className = e.className.replace(' over', ''); }, 1000)
}
</script>
Add css
#nav .over div.submenu
{
display: block;
}
#nav .nav_element{
behavior: expression(
this.onmouseover = new Function("this.className += ' over'"),
this.onmouseout = new Function("ddlOut(this)"),
this.style.behavior = null
);
}
It will work better at least but of course not perfect.
My advice is to change select control to html equivalent. I use OboutDropDown that has a nice view. There are many implementations that can suite you needs.
First you need to expand the :hover surface underneath your menu.
So in your css add width:310px;height:220px to #nav .nav_element a.
(also add a class or an id on the second div styled with top:220px)
Now you just need to simulate a mousedown triggered when you click on the select which will halt when the selection between the options is done - you can probably do the last part if you check for the onfocus state of the select which will stop the mousedown.

iframe height not taken into account by IE8

I'm building a dummy widget for a iGoogle/Netvibes like portal. This is a "Google Maps" widget, as it only renders a map centered on a specific location.
The widget looks good in all browsers but IE8, in which the height I specify to the <div> that contains the map is not taken into account.
Here's the interesting part of the code:
<body onload="initialize()" >
<div id="map_canvas" style="height:400px; width: 100%;"></div>
</body>
I have no control on the portal, so the only thing I can modify is the widget itself. I also tried to set the height for the <body>, but same thing.
Any idea on why it's not working in IE?
Thanks!
Put this in the page you're calling with the iframe:
<script type="text/javascript">
var iframes = window.parent.document.getElementsByTagName('iframe');
for(var i = 0; i < iframes.length; i ++)
{
if(iframes[i].src == window.location)
{
iframes[i].style.height = '400px';
}
}
</script>
If you are on 2 different domains, this isn't possible, and unfortunately there is no other way when supplying the <iframe> directly to the end-user. The best solution would be to instead give the user a script tag that generates the <iframe> tag using a document.write()
Example script tag to give to your client:
<script type="text/javascript" src="http://www.example.com/widget-getter.js?client=[clientid]&widget=[widgetid]"></script>
Contents of the script that the above tag would call:
document.write('<iframe height="400px" src="http://www.example.com/widget.html"></iframe>');
Did you try using the height attribute of the iframe tag?

Resources