Passing a variable from Jquery into HTML - html

I have a jquery function that works out the width and height of an image I upload through umbraco. How can I call this.width and this.height into my img src in html at the bottom of the page?
<script>
function getMeta(varA, varB) {
if (typeof varB !== 'undefined') {
alert(varA + ' width ' + varB + ' height');
} else {
var img = new Image();
img.src = varA;
img.onload = function () {
getMeta(this.width, this.height);
}
}
}
getMeta("#image.Url()")
</script>
<img src="#image.Url()" width="" height="" border="0" alt="#Model.Value("mapImage")
mapImage" usemap="#Map" />
I've left the width and height empty but that's where I want it to equal this.width and this.height. I need it to automatically call it for other functions I have as it needs to change depending on the size of the image uploaded.
Thanks in advance for any help :)

Well.. good news - this is native JS - no jquery used the code you've posted
Second - you don't need to send the width and height to your data model - just update your image element. so...
img.onload = function () {
const imgElement = document.querySelector('img'); // select the image element in you HTML page
imgElement.style.width = `${this.width}px`; // set a proper with using pixels as unit
imgElement.style.height = `${this.height}px`; // set height the same way
}
This should update your image proportions to be an exact fit to the image provided

Assuming that I understood you well and you have an uploaded pic (that you get its source by calling #image.Url()), and you want to apply its dimensions of another pic (with id templateImg), this is the code:
<img id="templateImg" src="https://cdn.vox-cdn.com/thumbor/prZDWmD_4e4Js7KCRJ2JDrJOqO0=/0x0:939x704/1400x1050/filters:focal(0x0:939x704):format(jpeg)/cdn.vox-cdn.com/uploads/chorus_image/image/49610677/homersimpson.0.0.jpg" />
<script type = "text/javascript">
var uploadedPic = 'https://i.pinimg.com/736x/dd/50/38/dd5038cdbfde2a8f1583bd84f992f862.jpg';
function getMeta(src) {
return new Promise(resolve => {
var img = new Image();
img.src = src;
img.onload = function () {
resolve({
width: this.width,
height: this.height
});
}
})
}
getMeta(uploadedPic)
.then(dimensions => {
document.getElementById('templateImg').style.width = `${dimensions.width}px`;
document.getElementById('templateImg').style.height = `${dimensions.height}px`;
});
</script>
It was working example with real pictures, now you just replace the line var uploadedPic... with this Razor code:
<text>
var uploadedPic = '#image.Url()';
</text>
(assuming this is the path to your uploaded picture) and you'll be fine.

Related

Adding image in the body of the email using href

I have a link in my page that once click it will open the email client.
My code is below:
<a href="mailto:?subject=Testing&body=AttachImage">
My question is how can I add an image in the body of the email. I tried image src but it does not work. Any suggestions?
Suppose you have your image defined like :
<img id="myimage" src="http://www.myserver.com/images/myimage"></img>
And its equivalent base64 encoded here that you would like to send by mail :
<img id="b64" src=""></img>
You can use base64 encoded form, such as :
function getBase64Image() {
//return LOGO;
var dataURL = '';
try {
var img = document.getElementById('myimage');
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to guess the
// original format, but be aware the using "image/jpg" will re-encode the image.
dataURL = canvas.toDataURL("image/jpg");
}
catch(e) {
console.log('Could not retrieve Base64 image with userAgent : ' + navigator.userAgent + ' \nException : ' + e);
}
return dataURL;
}
var base64Image = getBase64Image();
And then set your img src :
document["b64"].src = base64Image ;
Add that image inside <a> tag.
<a href="mailto:?subject=Testing">
<img src="your image path">
</a>
Hope it will help.
It's working, you might have not defined img width and height.
img{
width:100px;
height:100px;
}
<a href="mailto:?subject=Testing&body=AttachImage">
<img src = "https://source.unsplash.com/random">
</a>

Validate height width with bootstrap validator

$('#ad_pd_form').bootstrapValidator({
fields: {
ad_pd_image: {
validators: {
file: {
extension: 'jpg,png',
type: 'image/jpg,image/png',
maxSize: 30(Height) * 30 (width),
message: 'The selected file is not valid'
}
}
}
}
});
Friends i'm validating an image in bootstrap validator , I have to validate the height and width of the uploaded image , how to achieve this concept by using bootstrap validator . I need to upload only the image with size of 30 * 30 .
You Need to Suppurate validation function for the Image upload Check Dimension.
Here is the Sample Code:
$(function () {
$("#upload").bind("click", function () {
//Get reference of FileUpload.
var fileUpload = $("#fileUpload")[0];
//Check whether the file is valid Image.
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
if (regex.test(fileUpload.value.toLowerCase())) {
//Check whether HTML5 is supported.
if (typeof (fileUpload.files) != "undefined") {
//Initiate the FileReader object.
var reader = new FileReader();
//Read the contents of Image File.
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
//Initiate the JavaScript Image object.
var image = new Image();
//Set the Base64 string return from FileReader as source.
image.src = e.target.result;
image.onload = function () {
//Determine the Height and Width.
var height = this.height;
var width = this.width;
if (height > 100 || width > 100) {
alert("Height and Width must not exceed 100px.");
return false;
}
alert("Uploaded image has valid Height and Width.");
return true;
};
}
} else {
alert("This browser does not support HTML5.");
return false;
}
} else {
alert("Please select a valid Image file.");
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="file" id="fileUpload" />
<input id="upload" type="button" value="Upload" />

Static max/min width for an img of arbitrary size

The max- and min-width attributes on an <img> tag are very useful, particularly the max width which can prevent an img from streching larger than its original size.
Now this is easy when you are using a specific image, so you can set it to be the same as the size of the image. But what if you want to apply this to a general image, for example one which is uploaded by a user? (so you don't know what the dimensions are) In other words, set the max/min width to the exact dimension of the image, for an arbitrary image.
this should do it...
<html>
<script src="http://code.jquery.com/jquery-1.11.1.min.js">
</script>
...
<div id="img-container"></div>
...
</html>
<script>
function loadImage(imgSrc) {
var newImg = new Image();
newImg.onload = function() {
var height = newImg.height;
var width = newImg.width;
$(newImg).css({
'max-width':width,
'max-height':height
});
$("#img-container").append(newImg);
}
newImg.src = imgSrc; // this must be done AFTER setting onload
}
loadImage('youimage.jpg');
</script>
you could also use server side code to get the image size.
try like this
var _URL = window.URL || window.webkitURL;
$("#file").change(function(e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function() {
alert(this.width + " " + this.height);
};
img.onerror = function() {
alert( "not a valid file: " + file.type);
};
img.src = _URL.createObjectURL(file);
}
});
Working demo:
http://jsfiddle.net/4N6D9/1/

how to modify image changer ajax script

i have a script that changes the current image with the selected image but i need to insert an attribute so that it targets the image tag with only that class
CODE----
<script>
$(function(){
Test = {
UpdatePreview: function(obj){
// if IE < 10 doesn't support FileReader
if(!window.FileReader){
// don't know how to proceed to assign src to image tag
} else {
var reader = new FileReader();
var target = null;
reader.onload = function(e) {
target = e.target || e.srcElement;
$("img").attr(".the_pre_prev").prop("src", target.result);// tried $("img").attr("CLASS NAME").prop("src", target.result)
};
reader.readAsDataURL(obj.files[0]);
}
}
};
});
If you want to target an image with an specific class, you can simply do (assuming you're using jQuery):
$("img.the-class").attr("src", target.result)
See the jQuery class selector for reference.

How to call JavaScript to draw in a canvas for each table row?

I have an ASP.NET Razor View like this:
#{
this.Layout = null;
}
<script type="text/javascript">
function drawWindArrow(canvas, windDirection) {
// Draw something
}
</script>
<table style="width: 100%">
#foreach (var weather in ViewBag.WeatherForecastList)
{
double windDirection = weather.WindDirection;
<tr>
<td>
<canvas width="32" height="32"></canvas>
How can I call drawWindArrow with the canvas and the windDirection as a parameter???
</td>
</tr>
}
</table>
I would like to draw something in the canvas that is different for each row in the table. It should look similar to the arrows found here: http://www.yr.no/sted/Norge/Oslo/Oslo/Oslo/, but I don't want to use static images, since I need to draw with different colors based on some CSS3 styles.
How can I call the drawWindArrow JavaScript function with the canvas and the windDirection as a parameter?
You want create an object for your arrow thing. This should get you on the right foot.
var TableCanvasObject = function (arrowDirection, arrowType, container, id) {
this.container = container;
this.canvas = null;
this.ctx = null;
this.createArrow = function () {
if (arrowType == "foo") {
//draw arrow foo
} else if (arrowType = "boo") {
//draw arrow boo
}
};
this.create = function () {
this.canvas = document.createElement("canvas");
this.canvas.id = id;
this.ctx = this.canvas.getContext("2d");
this.createArrow();
};
this.create();
this.display = function () {
container.append(this.canvas);
}
};
window.onload = function () {
var obj = new TableCanvasObject(90, "foo", document.getElementById("con"), "my thing");
obj.display();
};
I have finally written well working code.
This is how I did it:
1) Define my Canvas inside the element in my ASP.NET Razor View. Notice the usage of the HTML5 data attributes on the Canvas element. They are used to pass values to my JavaScript function that will draw the weather arrows inside the canvas element:
<td>
#string.Format("{0:f1}m/s ", weather.WindSpeed)
<canvas width="32" height="32" data-windSpeed="#(weather.WindSpeed)" data-windDirection="#(weather.WindDirection)">
</canvas>
<br />
#weather.WindSpeedName
</td>
2) The JavaScript function is called after the HTML content is loaded to draw the content into all the canvas elements that are located under a specific table element:
function drawWindArrows() {
$('#weather canvas').each(function () {
var parent = this.parentNode;
var style = window.getComputedStyle(parent, null);
var color = style.color;
var windSpeed = $(this).attr('data-windSpeed');
var windDirection = $(this).attr('data-windDirection');
drawWindArrow(this, color, windSpeed, windDirection);
});
}
function drawWindArrow(canvas, color, windSpeed, windDirection) {
// Draw inside the canvas
}
You can see the finished web page here:
http://olavtlocation.cloudapp.net/weather