Vladimir Savić
Vladimir Savić

Reputation: 57

How to change style of an element on another page using JavaScript or jQuery?

Ok, this is my problem... I have two pages. On the first page I have a header (h2) element on which I want to apply a border style. On the second page, there is only one link. When clicking on the link from the second page, to navigate to the first page, it should create a border on the first page around the h2 tag.

Any thoughts on how to do this? Is it possible to do it with regular JavaScript or jQuery?

Thanks!

Upvotes: 1

Views: 3184

Answers (4)

Jai
Jai

Reputation: 74738

I think if you are looking this kind of scenario you can achieve it with passing some hash to the url:

i passed a hash named 'second' in the second page url and put this script on second page

$(function(){
    var url=window.location;
    var hash = url.hash.substr(1);
    if(hash == "second"){
       $('h2').css('border','solid 1px red');
    }
});

Checkout this if helps.

Upvotes: 1

antila
antila

Reputation: 364

It would be a pretty stupid way of doing it, but it is possible to do it client side. I would seriously recommend to do it server-side though.

On page 2, link back to page 1 with a hash:

<a href="/page1#border">Go back to page one and add a border</a>

And on page 1, check if there's a hash:

if (window.location.hash === '#border') {
    $('h2').addClass('withBorder');
}

Upvotes: 1

Jason Sperske
Jason Sperske

Reputation: 30446

Well there is a way you could do this with JavaScript, although it's tricky and server side is a LOT easier. You would need to use some JavaScript to load different pages without refreshing the entire DOM. I do this with something called pjax. The way it works is to have each page act as a container to load all subsequent pages via ajax. By not doing a full page reload, any style changes you make on one page get carried over to other pages (this dose not survive an actual browser refresh).

Upvotes: 0

Tom Walters
Tom Walters

Reputation: 15616

No, JavaScript is client-side and for this you would require the server to remember if the link was clicked, possibly by recording this in a database or session variable.

That's of course if you're using the tradition model of a website, rather than loading pages already using pure JS.

Upvotes: 1

Related Questions