"getting screen width into javascript variable and sending it through ajax to a php page to avoid page load" Code Answer

5

i'm not sure if i understood your problem but this is what i've got: if you only intend to get the screen width and then set the class i disencourage you to do it that way. it's not nice and in the future if you need to change your page layout you'll be doomed by having all those echo in php and you'll avoid a lot of redirects (index.html -> process.php -> index.php).

by your example you can do it all in javascript.

this is example is with jquery

var width = $(window).width(); //get the width of the screen
$('#wrapper').css("width",width); //set the width to the class

if the idea is for very different screen resolutions (from pcs to smartphones), you should consider changing your approach.

good luck :)


try this: (i believe is what you want)

you can do this with just js and css. here is an example:

set the style for your body margin and your test div:

<style type="text/css">
    body {
        margin: 0px 0px 0px 200px;
}
    .divfortesting {
        width: 250px;
        border: 1px solid green;
        height: 100px;
        float: left;
}
</style>

then add this script:

<script>
    // get the screen width
    var width = $(window).width();
    // get the number of pixels left in the screen (which is the width
    // minus the margin you want, rest by 250px which is the "inner boxes" width)
    var size = (width - 200) % 250;
    // then re-set the margin (the "-10" is because you'll need extra space
    // for borders and so on)
    $('body').css("margin-left",200+(size-10));
</script>

and test it with this html:

<!-- i've aligned the outter div to the right -->
<div style="border: 1px solid red; float:right;" id="test">
<div class="divfortesting">test</div>
<div class="divfortesting">test</div>
<div class="divfortesting">test</div>
<div class="divfortesting">test</div>
<div class="divfortesting">test</div>
<div class="divfortesting">test</div>
<div class="divfortesting">test</div>
<div class="divfortesting">test</div>
<div class="divfortesting">test</div>
</div>

it works in different resolutions.

give it a try :)

By Thomas Gratier on October 11 2022

Answers related to “getting screen width into javascript variable and sending it through ajax to a php page to avoid page load”

Only authorized users can answer the Search term. Please sign in first, or register a free account.