Reputation: 241
I am trying to automatically generate rounded values with the floor function but it stays static. Can you please help me how to improve my code ? Thank you very much.
jQuery:
$(document).ready(function() {
width_split = $(document).width();
width_split = Math.floor(width_split / 2);
$(document).resize(function() {
width_split = $(document).width();
width_split = Math.floor(width_split / 2);
});
});
HTML:
<p style="position:absolute; right:"+width_split+"px;">
.content
</p>
Upvotes: 1
Views: 2386
Reputation: 13702
Select each element you wish to adjust and apply the style directly
$('.your-selector').css({theProperty: halfWidth});
But this way you have to modify the js for every new element that you add to the html.
Put a marker (MRK) class on "reactive" objects, and include in the marker also the css property you want to set to be width/2 (eg. MRK-left, or MRK-margin-left)
Then on window resize, search for the elements that contain the marker, extract the css property, and set it on them.
$(window).on('resize', function () {
var halfWidth = $(window).width() / 2;
$('*[class*=MRK-]').each(function(){ // selects all elements having a class
var cls = $(this).attr('class') // property that contains MRK
var cssPropName = /MRK-([\w-]+)/.exec(cls)[1]; // extracts the info MRK
var css = {};
css[cssPropName] = halfWidth; // creates the styleobject with the info
$(this).css(css);
});
});
In html you would write:
<div class="MRK-left"></div>
or
<p class="MRK-margin-left"></p>
The result at 800px width would be:
<div class="MRK-left" style="left: 400px"></div>
or
<p class="MRK-margin-left" style="margin-left: 400px"></div>
And you can change like this any property without changing the js logic
Upvotes: 0
Reputation: 6349
Apply the width_split
for <p>
tag by jquery, the way you are appying width_split
at inline p
tag is wrong. Something like should be
Html
<p id="para" style="position:absolute"; >
.content
</p>
js
$("#para").css("right", width_split + "px");
instead of
<p style="position:absolute; right:"+width_split+"px;">
///--------------------------this is wrong---^
Upvotes: 0
Reputation: 1207
You should also update HTML tag
$('pID').css('right', width_split.toString()+'px');
Inside the document.resize function.
Upvotes: 0
Reputation: 12213
You have to set right
value inside your JS not in the HTML DOM
Try:
HTML:
<p id="mypar" style="position:absolute;">
.content
</p>
JS:
$(document).ready(function(){
width_split = $(document).width();
width_split = Math.floor(width_split / 2);
$(document).resize(function(){
width_split = $(document).width();
width_split = Math.floor(width_split / 2);
$('#mypar').css("right", width_split+'px');//ADD THIS
});
$('#mypar').css("right", width_split+'px');//ADD THIS
});
Upvotes: 1