Youssef DRISSI Youssef DRISSI - 7 months ago 17
PHP Question

change existant CSS class proprety with jQuery and PHP

i'm new with jQuery !
i have a CSS file named "Slider.css" that contains the following code :

.banner1 {
/*background: url(../images/bnr1.jpg) no-repeat 0px 0px;*/
background-size: cover;
min-height: 650px;
}

.banner2 {
/* background: url(../images/bnr2.jpg) no-repeat 0px 0px;*/
background-size: cover;
min-height: 650px;
}

.banner3 {
/* background: url(../images/bnr3.jpg) no-repeat 0px 0px;*/
background-size: cover;
min-height: 650px;
}


what i want is to change the url of the background in page called home.ctp according to data that i get from database so i tried this :

<?php $i=1; ?>
<?php foreach ($query as $slider): ?> // query contain 3 items
<div class="slid banner<?= $i; ?>">
<div class="caption">
<h3><?= $slider->titre; ?></h3>
<p><?= $slider->contenue; ?></p>
<a href="#" class="button">know more</a>
</div>
</div>
<script>
// alert(".banner<?= $i; ?>");
$(".banner<?= $i; ?>").css({"background": "url(../images/<?= $slider->url ?>) no-repeat 0px 0px;"})
</script>
<?php $i++; ?>;
<?php endforeach; ?>


So i tried
$(".banner<?= $i; ?>").css({"background": "url(../images/<?= $slider->url ?>) no-repeat 0px 0px;"})
but it doesn't change anythnig..

How can i change the css of
Slider.css
from php Loop using jQuery !
Thanks for help

Answer

Basically, you're doing it wrong. You don't need and shouldn't be using jQuery for this.

This is what you want:

.banner {
  background-size: cover;
  min-height: 650px;
}
<?php foreach ($query as $slider): ?>// query contain 3 items
<div class="slid banner" style="background: url(../images/<?= $slider->url ?>) no-repeat 0px 0px;">
  <div class="caption">
    <h3><?= $slider->titre; ?></h3>
    <p>
      <?=$ slider->contenue; ?></p>
    <a href="#" class="button">know more</a>
  </div>
</div>
<?php endforeach; ?>