Search code examples
phpjavascriptdynamic-css

Generating dynamic css using php and javascript


I want to generate tooltip based on a dynamically changing background image in css. This is my my_css.php file.

<?php
    header('content-type: text/css'); 
    $i = $_GET['index'];
    if($i == 0)
        $bg_image_path = "../bg_red.jpg";   
    elseif ($i == 1)
        $bg_image_path = "../bg_yellow.jpg";   
    elseif ($i == 2)
        $bg_image_path = "../bg_green.jpg";   
    elseif ($i == 3)
        $bg_image_path = "../bg_blue.jpg";    
?>
.tooltip {
            white-space: nowrap;
        color:green;
        font-weight:bold;
            border:1px solid black;;
            font-size:14px;
        background-color:  white;
        margin: 0;
        padding: 7px 4px;
        border: 1px solid black;
        background-image: url(<?php echo $bg_image_path; ?>);
        background-repeat:repeat-x;
        font-family: Helvetica,Arial,Sans-Serif;
        font-family: Times New Roman,Georgia,Serif;
        filter:alpha(opacity=85); 
        opacity:0.85;
        zoom: 1;
 }

In order to use this css I added

<link rel="stylesheet" href="css/my_css.php" type="text/css" media="screen" />

in my html <head> tag of javascript code. I am thinking of passing different values of 'index' so that it would generate the background image dynamically. Can anyone tell me how should I pass such values from a javascript ? I am creating the tooltip using

var tooltip = document.createElement("div");
document.getElementById("map").appendChild(tooltip);
tooltip.style.visibility="hidden";

and I think before calling this createElement, I should set background image.


Solution

  • You seem to be asking two completely independent questions.

    First, the way to pass a parameter would be in your <link> tag:

    <link rel="stylesheet" href="css/my_css.php?index=3" type="text/css" media="screen" />
    

    When the page loads, the browser will request the css/my_css.php?index=3 page from your server and use the CSS that gets returned.

    However, you're also asking about setting this value with JavaScript. That suggests that you want the CSS to change throughout the request. In that case, PHP is absolutely the wrong technology to be using.

    Instead, consider adding classes like:

    .tooltip-background-1 {
        background-image: url(../bg_red.jpg);
    }
    

    Then you do not need any dynamic content in the CSS file. Just include all four (or more) rules at once, and use JavaScript to change which class applies to the element.

    Finally, if you goal is simply to choose a random background color, you could just let PHP choose the random value, eliminating any need for a parameter or for JavaScript and PHP to interact at all.