ever-evolving background-image with dynamic CSS styling

Being new to both PHP and Javascript, please excuse any mistakes in my explanation. I have information stored in a PHP array that I bring to my index page using the function below (located in a separate file called articles.php that is included in my index.php):

<?php

function get_news_feed($article_id, $article) {

  $output = "";

  $output .= '<article class="img-wrapper">';
  $output .= '<a href="article.php?id=' . $article_id . '">';
  $output .= '<div class="news-heading">';
  $output .= "<h1>";
  $output .= $article["title"];
  $output .= "</h1>";
  $output .= "<p>";
  $output .= "Read more...";
  $output .= "</p>";
  $output .= "</div>";
  $output .= '<div id="news-img-1">';
  $output .= "</div>";
  $output .= "</a>";
  $output .= "</article>";

  return $output;
} 

$articles = array();
$articles[] = array(
  "title" => "Andy at NABA",
  "description" => "Docendi, est quot probo erroribus id.",
  "img" => "img/gym-01.jpg",
  "date" => "05/04/2013" 
);
$articles[] = array(
  "title" => "Grand Opening",
  "description" => "Docendi, est quot probo erroribus id.",
  "img" => "img/gym-01.jpg",
  "date" => "05/04/2013" 
);

?>

My index.php contains the following code:

<?php 
include("inc/articles.php");
?>

<?php
$pageTitle = "Home";
include("inc/header.php"); 
?>

<section class="col-4 news">

    <?php

    $total_articles = count($articles);
    $position = 0;
    $news_feed = "";

    foreach($articles as $article_id => $article) {

    $position = $position + 1;
        if ($total_articles - $position < 2) {
            $news_feed .= get_news_feed($article_id, $article);
        }
    } 

    echo $news_feed;

    ?>

</section>

I am trying to dynamically change the CSS Background-Image property of the div element with ID news-img-1 using Javascript.

I have attempted various methods, such as:

document.getElementById('news-img-1').style.backgroundImage = 'url('<?php $article["img"]; ?>')';

document.getElementById('news-img-1').style.backgroundImage = 'url('http://www.universalphysique.co.uk/' + '<?php $article["img"]; ?>')';

document.getElementById('news-img-1').style.backgroundImage = 'url('window.location.protocol + "//" + window.location.host + "/" + '<?php $article["img"]; ?>')';

However, none of these solutions seem to work. An example where an image is correctly inserted is:

document.getElementById('news-img-1').style.backgroundImage = 'url("img/gym-01.jpg")';

Here is my site up and running, but the images are not appearing in the empty circles as intended. Any assistance would be greatly appreciated!

Answer №1

When comparing hardcoded JavaScript to those that do not function properly, it becomes evident that the issue lies in the absence of double quotes around the <?php $article["img"]; ?> snippet. The hardcoded version displays

= 'url("img/gym-01.jpg")'

while the PHP snippets will result in

 = 'url(img/gym-01.jpg)'

By adjusting the code to

document.getElementById('news-img-1').style.backgroundImage = 'url("'<?php $article["img"]; ?>'")';

OR

modify the get_news_feed function as follows:

replace these lines

$output .= '<div id="news-img-1">';
$output .= "</div>";

with

$output .= '<div class="news-img"><img src="' . $article["img"] . '"></div>' ;

and make changes to your CSS like this:

article.img-wrapper {
    position: relative;
}

div.news-img {
    position: absolute;
    top: 0;
    z-index: -1000;
}

OR

Revise your get_news_feed function, update the statement for the <div id="news-img-1"> output to incorporate a data-url attribute such as:

$output .= '<div class="news-img" data-url="' . $article["img"] . '">';

Then insert a jQuery statement:

$(".news-img").each( function() { 
        $(this).css("background-image", "url(" + $(this).data("url") +")" ); 
    });

The jQuery statement should be placed in a static JS file instead of being generated within PHP.

Answer №2

To make your PHP tags work, try removing the quotes and testing it out!

Here's how you can do it:

document.getElementById('news-img-1').style.backgroundImage = 'url(' + <?php $article["img"]; ?> + ')';

I trust this solution will be useful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Showcasing or concealing.JSON data depending on the selected item in a React and MaterialUI application

Looking to enhance the user experience, I am developing a dynamic FAQ section sourced from a JSON file containing an array of objects with 'Question' and 'Answer'. https://i.stack.imgur.com/mljpm.png The functionality is such that click ...

Customize the underline color of Material-UI's Input component

Trying to create an input component with a white underline. However, the underline color changes to black when hovering over it. It should remain white. Override the underline class as shown in the demo and instructions below. Despite trying to implement t ...

When using PHP in Wordpress, the previous post link may unexpectedly display on the final post in the

Essentially, the following code displays the next category of posts instead of omitting it. <div class="post-previous"><?php previous_post_link('%link', true); ?></div> I would expect this to be hidden if it's in the last ...

What are ways to boost the speed of an Ajax-php-xml chat application?

I developed a chat application using Ajax-php-xml technology. Everything runs smoothly when there are fewer than 50 users, but once the user count crosses 50, the performance drastically slows down. My goal is to efficiently manage up to hundreds of users ...

What is the best way to choose a tag from an app within components or views?

In my main component file, I added a color picker input in the navigation section to change the background color of the application. This works fine as the body tag can be accessed easily within the DOM. Furthermore, I store the selected color in local st ...

Combine multiple jQuery click functions into a single function

One issue I am facing on my website is that there are multiple modules, each of which can be disabled by the user. The problem lies in the fact that I have a separate script for each module. Hence, my query: How can I combine these scripts into one (perhap ...

Determine the value of a field by utilizing the values of two other fields through an onChange event

Setting the Stage: Imagine a scenario with 3 key fields: quantity, singlePrice, and totalPrice. I want these fields to be part of my form, with totalPrice being dynamically recalculated whenever quantity or singlePrice changes. My Approach: I created ...

The file_get_contents() function is unexpectedly returning false when provided with a correct URL

Currently, I am in the process of developing a geocoding PHP function that utilizes the Google Maps API. It seems like there is an issue with the file_get_contents() function returning bool(false), even though the URL I have encoded appears to be correct. ...

What is the best way to transfer JSON data to a different controller in AngularJS?

Hello, I'm still learning AngularJS and facing an issue with the following code snippet. app.config(function($routeProvider) { $routeProvider .when('/', { templateUrl: "partials/home.html", controller: "mainControlle ...

What is the best method to incorporate extra parameters into highcharts using data extracted from datatables?

I have a query regarding the integration of datatables with highcharts. The issue I'm facing is related to specific configurations for chart-A, which is of column type. Even after applying the configurations, it seems like they are not being incorpora ...

Tips for positioning a highcharts pie chart and legend in the middle of a page

I'm struggling to center my highchart data in a node/react single page application. Currently, it appears off-center like this: https://i.stack.imgur.com/ccR6N.png The chart is floating to the left and I would like to have everything centered within ...

Stopping videos in the JQuery Cycle Plugin triggers the stop event

Currently, I have a simple cycle set up with YouTube videos using the following code: <script type="text/javascript"> $(document).ready(function () { $('#cycle').cycle({ fx: 'fade', sp ...

Retrieve the total count of tables within a specific div element

If I have an unspecified amount of tables within a div, how can I determine the total number of tables using either plain JavaScript or jQuery? ...

"Utilize Vue i18n to properly display currency amounts in USD

Whenever I present my currency as USD, it always shows up like this: USD$500.00. I am attempting to eliminate the USD prefix from the beginning. Below is my numberFormats configuration: numberFormats: { 'en': { currency: { ...

AngularJS : Resolving Alignment Issues with ng-repeat and ng-include

The ng-repeat feature is being utilized here with an inclusion of a different HTML partial. <div ng-repeat="item in feedItems"> <div ng-include="'item.itemType.html'"> </div> </div> Below is the CSS for the partial H ...

Additional cushioning is added when utilizing the X-UA-Compatible meta tag

After experimenting with various meta tags in the <head> section of my static HTML page, I have found that using <meta http-equiv="X-UA-Compatible" content="IE=edge" /> allows me to access newer CSS elements such as table:last-of-type in IE9. ...

I am looking to create a div that can consistently refresh on its own without needing to refresh

I have implemented a comment system using ajax that is functioning well. I am looking to incorporate an ajax/js code to automatically refresh my "time ago" div every 5 seconds so that the time updates while users are viewing the same post. Important note: ...

The Art of Determining the Text's Baseline

My goal is to create a test that determines whether the text rendered inside an <input> has the same baseline as a label: To achieve this, I want to calculate the baseline of the rendered text in each element and compare their values. Is it possible ...

Likelihood of triggering a function based on percentage

Hey everyone, I'm looking to add some randomness to the buttons on my website. I have a Button that could activate function one, function two or function three. However, I want to make it so there is a 60% chance that function one gets called from the ...

What is the best way to remove data from both arrays simultaneously?

I am working with a grid that displays a list of time ranges. For example: timeList=[{from:12:00:00 , to:14:00:00 ,id:10}{from:08:00:00 , to:09:00:00 ,id:11{from:05:00:00 , to:10:00:00 ,id:12}}] time=[{Value:12:00:00 id:10} {Value:14:00:00 id:100} ...