Amir Sasani
Amir Sasani

Reputation: 327

Changing the dimensions of element

I want to change many elements (figcaption) dimensions to img dimensions with jquery plz help me

var width = $("div[caption='true'] img").attr("width");

var height = $("div[caption='true'] img").attr("height");

$("div[caption='true'] figcaption").css("width",width);
$("div[caption='true'] figcaption").css("height",height);

jsfiddle link

Upvotes: 4

Views: 78

Answers (3)

Doug Leary
Doug Leary

Reputation: 318

You can do it by using a function to fill in the css value:

$(document).ready( function() {
  $("img + figcaption")
    .css("width",function() { return $(this).prev().attr("width");})
    .css("height",function() { return $(this).prev().attr("height"); });
});

This will match any <img> followed by <figcaption> - there is no need for the caption="true" attribute, unless you are using it for something else.

Upvotes: 0

Jazi
Jazi

Reputation: 6712

Try this:

$(function() {
    $("div[caption='true']").each(function() {
        var $this  = $(this);
        var image  = $this.find('img')
        var width  = image.width();
        var height = image.height();

        $this.find('figcaption').width(width).height(height);
    });
});

jsFiddle: http://jsfiddle.net/8ge1wvpt/11/

Upvotes: 1

Turnip
Turnip

Reputation: 36632

Your current code is setting each figcaption's height and width to that of the first image. Try this:

$(document).ready( function() {

    $("div[caption='true']").each(function() {
        var $this = $(this);
        var width = $("img", $this).attr("width");
        var height = $("img", $this).attr("height");
        $("figcaption", $this).css({"height":height, "width":width});
    });

});

DEMO

Snippet below:

$(document).ready( function() {
	
	
    $("div[caption='true']").each(function() {
        var $this = $(this);
        var width = $("img", $this).attr("width");
        var height = $("img", $this).attr("height");
        $("figcaption", $this).css({"height":height, "width":width});
    });
	
});
*{margin:0;padding:0;}
.imgs{position:relative;}
figcaption{position:absolute;top:0;
    background-color:rgba(0,0,0,0.4);}
figcaption h3{text-align:center;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="imgs" caption="true">
  
   <img src="http://goo.gl/uRvjRS" width="200" height="250" alt=""/>
   <figcaption>
    <h3>IMGs Caption 1</h3>
   </figcaption>
  
  </div>
  
  <div class="imgs" caption="true">
  
   <img src="http://goo.gl/uRvjRS" width="100" height="100" alt=""/>
   <figcaption>
    <h3>IMGs Caption 2</h3>
   </figcaption>
  
  </div>
  
  <div class="imgs" caption="true">
  
   <img src="http://goo.gl/uRvjRS" width="300" height="200" alt=""/>
   <figcaption>
    <h3>IMGs Caption 3</h3>
   </figcaption>
  
  </div>

Upvotes: 0

Related Questions