Reputation: 77
I have a problem with setAttribute() . I have searched the internet and this website but they did not solved my problem . I want to change the width and height of a picture with javascript but it does not work . please help me.
<html>
<head>
<meta charset="utf-8"/>
<title>Width Height Changer</title>
<script type="text/javascript">
function chang(){
var wid = document.getElementById('width').value;
var hei = document.getElementById('height').value;
var set = document.getElementById('pic');
if(Number(wid) && Number(hei)){
set.setAttribute("style","width : wid");
set.setAttribute("style","height : hei");
}else{
alert('Error');
}
}
</script>
</head>
<body>
<input type="text" id="width" placeholder="Enter Width"/>
<input type="text" id="height" placeholder="Enter Height"/>
<button onclick="chang()">OK</button><br/>
<img src="back4.jpg" id="pic" />
</body>
Upvotes: 0
Views: 3392
Reputation: 1356
Recommend a few changes as well to improve readability. Using an id="width" and "height" is confusing since width/height are also JS/html keywords. Also some additional error checking never hurts:
function chang(){
var wid = document.getElementById('inputWidth').value;
var hei = document.getElementById('inputHeight').value;
var set = document.getElementById('pic');
if(Number(wid) && Number(hei) && set && set.style){
set.style.setAttribute("width", wid + "px");
set.style.setAttribute("height",hei + "px");
}else{
alert('Error');
}
}
Upvotes: 0
Reputation: 5060
better to use:
set.style.width = wid +"px";
set.style.height =hei+"px";
function chang(){
var wid = document.getElementById('width').value;
var hei = document.getElementById('height').value;
var set = document.getElementById('pic');
if(Number(wid) && Number(hei)){
set.style.width = wid +"px";
set.style.height =hei+"px";
}else{
alert('Error');
}
}
Upvotes: 2
Reputation: 126
Your variables are treated as strings since they are quoted - change to:
if(Number(wid) && Number(hei)){
set.setAttribute("style","width :" + wid + "px");
set.setAttribute("style","height :" + hei + "px");
} else {
Upvotes: 0
Reputation: 100205
you can use:
set.style.width = wid + "px";
set.style.height = hei + "px";
or
set.style.setAttribute("width", wid + "px");
set.style.setAttribute("height",hei + "px");
Upvotes: 0