duukn
duukn

Reputation: 275

Changing the text position based on width of a button

I am dealing with some responsive design and would like to move the text in a button if certain string is above 37 characters AND if the width of a button is above a certain width.

So far I managed to move the text based on the string.length however when I introduce the second condition I am having issues.

<div class="button">
  <p>I am a button<p>
</div>

I also have a list of variables that change the text in the button based on some previous result. Here is what I have tried:

//searches my list for what text to put
var textLength = list[country].text.length

//trying to find the width of the button 
var buttonLength = $('.button').width();

//display the width, do not see it in dev tools, having issue here
console.log(buttonLength);

          if(textLength > 37 && buttonLength > 309 ){
           $('.button p').css('bottom', '0.9em'); 
          };

I believe that the problem may lay with my syntax. Any input is much appreciated.

Upvotes: 0

Views: 313

Answers (1)

Pierre Burton
Pierre Burton

Reputation: 2084

...Would like to move the text in a button if certain string is above 37 characters AND if the width of a button is less than a certain width.

Thus, your if statement is :

if(textLength > 37 && buttonLength > 309 )

You should try this :

if(textLength > 37 && buttonLength < 309 )

EDIT :

As the if statement is not the issue, I assume your div has a padding css property which is not computed with .width() method. Instead use .outerWidth() as mentionned in jQuery's doc:

Get the current computed outer width (including padding, border, and optionally margin) for the first element in the set of matched elements or set the outer width of every matched element.

Here's a working fiddle :

var textLength = $('#text').html().length,
		divWidth = $('#test').outerWidth();

if (textLength > 14 && divWidth > 300) {
	alert("Text is "+ textLength + " characters, div is " + divWidth+ "px wide");
  $('#text').css('transform', 'translateY(0.9em)');
}
else {
	alert("Not in condition");
}
#test {
  display: block;
  float: left;
  padding: 0 100px;
  background: springgreen;
  width: auto;
  position: relative;
}
#text {
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<div id="test">
<p id="text">fsqdfdgfdgfdfgdf</p>
</div>

Also, instead of bottom: 0.9em, use transform property.

Upvotes: 2

Related Questions