1

Is it possible to import css stylesheets to test.php head after redirect page to test.php after click on a href link from index page using Javascript? If so, how can it be done?

problem is that styles.css not working or display in test.php page?

i have code like this:

Index Page

<a id="some_id" class="optional_has_click">Click Me</a>

Jquery

<script type="text/javascript">
$(document).ready(function(){

$("#some_id").click(function(){

 // add dynamically css file from external link and display to head
 window.location.href = 'test.php'; 

var cssId = 'styles'; 
var head  = document.getElementsByTagName('head')[0];
var link  = document.createElement('link');
link.id   = cssId;
link.rel  = 'stylesheet';
link.type = 'text/css';
link.href = 'http://example.com/styles.css';
link.media = 'all';
head.appendChild(link);

document.write("<style>#jstree-marker-line, 
#preloader{ background:none !important}</style>");

});

});
</script>

test page

<div id="container">

<p>test</p>

</div>
  • See these posts for different ways of interaction between js and css http://davidwalsh.name/add-rules-stylesheets and http://davidwalsh.name/ways-css-javascript-interact So I guess the options are either loading the css file with curl.js or dynamically adding the rules to your present stlyesheets (or as an inline ` – alpipego Aug 15 '15 at 08:19

2 Answers2

0

You cannot use document.write after the page has loaded, but if you really want to add styles like this to the head of the page you could potentially try something like this:

$("head").append("<style>...</style>");

But, it's probably better to do something like this when you want to update a style on the page

$("#jstree-marker-line").css("background", "none");

Or you could have a class with the styles you need defined on the page and use jquery's addClass to add that class dynamically on click

  • problem is that `styles.css` not working or display in `test.php` page? –  Aug 15 '15 at 08:08
  • question is that when i click to `a href link` page redirect to `test.php` and styles.css should be apply in test.php –  Aug 15 '15 at 08:22
0

Using window.location.href = 'test.php'; will load a different page and stop any JavaScript running after that point.

Check out this question: How can I make JavaScript make (produce) new page? as it may answer your problem, or run the rest of the script on the test page.

Also check out @JenGettings' answer instead of document.write as it will overwrite the page.

Community
  • 1
  • 1
A. Hall
  • 71
  • 4