Pluda
Pluda

Reputation: 33

Replace attr width and height within string

I'm trying to play with resizable elements, in this case one image. it works, but I can't replace the original width and height of new dimentions, what I'm I doing wrong?

var codigo = '<div style="text-align: left;"><img src="../pics/bom.jpg" id="bom.jpg" title="" alt="" style="border: 1px solid;"  height="167px" width="167px"></div>';
// 

if(pic = $(codigo).find('img').attr('id', que_pic)) {
     alert(largura_final_imagem+" "+altura_final_imagem); // 400px
     alert($(pic).attr('width')+" "+$(pic).attr('height')); // 400px

     if($(pic).removeAttr('width')) {
       $(pic).attr('width', largura_final_imagem);
       if($(pic).removeAttr('height')) {
           $(pic).attr('height', altura_final_imagem);
       }
     } else {
        alert("Error resizing your image!");
     }
     alert($(pic).attr('width')); // 0
     alert($(pic).attr('height')); // 0
     novo_html = codigo;
     alert(novo_html); // same string without changes
  }

Thanks

Pluda

Upvotes: 1

Views: 4129

Answers (3)

Pluda
Pluda

Reputation: 33

it works mor or less :-)

if you add at the end this

`var txt_codigo = document.createElement('TEXTAREA'); txt_codigo.id = 'txt_codigo'; $(txt_codigo).css('width', '100%'); $(txt_codigo).css('height', '200px'); $(txt_codigo).val(novo_html); $("body").prepend(txt_codigo);

` you will notice that now the div container of the string is gone...

Thanks again

Pluda

Upvotes: 0

Mutation Person
Mutation Person

Reputation: 30520

I've modified your code to get it to work (also available at http://jsfiddle.net/ahwv6/1/). I had to add a few variables in as well, which you'll see below.

var codigo = '<div style="text-align: left;"><img src="../pics/bom.jpg" id="bom.jpg" title="" alt="" style="border: 1px solid;"  height="167px" width="167px"></div>';
// 
var largura_final_imagem = 100;
var altura_final_imagem= 100;
var $codigo = $(codigo);
var $pic = $codigo.find('img');


 alert(largura_final_imagem+" "+altura_final_imagem); 
 alert($pic.attr('width')+" "+$pic.attr('height')); 

 $pic.attr('width', largura_final_imagem);
 $pic.attr('height', altura_final_imagem);

 alert($pic.attr('width')); 
 alert($pic.attr('height')); 
 var novo_html = $codigo.html();
 alert(novo_html); // same string without changes

A lot of your checks were needless, so I removed them.

Hope this helps.

Upvotes: 0

Andrew Orsich
Andrew Orsich

Reputation: 53695

For get/set height/width use height and width functions.

For example:

var picHeight = $(pic).height(); // get height
$(pic).height(500); // set height

Upvotes: 1

Related Questions