TopDeveloper
TopDeveloper

Reputation: 542

How I can change the CSS properties of HTML elements in run time using JavaScript or PHP?

I developed a PHP website which contains php pages. These web pages have header and footer divisions. I put both the Header and Footer divisions in separate php files and I included them using the php include function.

The problem is that I have links to the main menu in the header and the footer php files.

Before using the include function, I used the CSS Class property of the link tag to display the currently selected link in a different format.

<a id="Link_Home" class="current">Home</a>
<a id="Link_AboutUs" >About Us</a>
<a id="Link_Branches" >Branches</a>
<a id="Link_Services" >Services</a>
<a id="Link_ContactUs" >Contact Us</a>

How can I do the same after using the include function?

Should I use JavaScript to pass the id or name of the link to be the current one with that specific format and style? If so, how do I do that?

Is there a way to use PHP directly to change the CSS properties of the HTML elements so that I can modify the class property during run time? How can I do that?

I appreciate your help and thanks in advance.

Upvotes: 0

Views: 427

Answers (2)

Toni Z
Toni Z

Reputation: 1

You could use ajax to load your page. I'm saying divide your page into 3 parts. #header, #content and #footer. You may add this using jQuery library:

//adding code to all a tags to manually deal links
$("#footer a").click( function(e){
    // check if this has class "current"
    if($(this).hasClass("current")){

    }else{
    //remove all class "current" and add one
    $('#footer a').removeClass("current");
    //add class "current" to the selected one
    $(this).addClass("current");
    //get location of the target link
        var url = $(this).attr("href");
        //prevent broswer default behavior, e.g. opening the link in a new window
        e.preventDefault();
       //load html from the given address to #content
       loadPage(url);
       }
});

function loadPage(url) {
    //adding a loading icon
    $('#content').html('<div id="progress"><img src="images/ajax-loader.gif" /></div>');
//when completed, remove the icon
    $('#content').load(url, function(){
        $('#progress').remove();
    });
}

This is just one solution. It helps you update the content of page without refreshing, so all your javascript data remain unchanged. Ajax makes your site faster.

Upvotes: 0

Shameer
Shameer

Reputation: 3066

If in php You can write class="current" inside a condition like.

<a id="Link_Home" <?php if($page == 'home'){echo 'class="current"';} ?> >Home</a>

Upvotes: 2

Related Questions