Youssef DRISSI
Youssef DRISSI

Reputation: 67

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

Upvotes: 3

Views: 57

Answers (2)

Jordi Nebot
Jordi Nebot

Reputation: 3401

You don't need jQuery to achieve this. If $slider->url contains the URL of your background image, just do:

<?php $i = 1; foreach ($query as $slider): ?>
  <div class="slid banner<?php echo $i; ?>" style="background-image: url(<?php echo $slider->url; ?>)">
    // ...
  </div>
<?php $i++; endforeach; ?>

Indeed, your CSS already defines the background image, you shouldn't even need this. Just the <div class="slid banner<?echo $i; ?>"> does the trick.

Upvotes: 3

Preston S
Preston S

Reputation: 2771

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; ?>

Upvotes: 5

Related Questions