how to get the base url in javascript
Solution 1:
Base URL in JavaScript
You can access the current url quite easily in JavaScript with window.location
You have access to the segments of that URL via this locations
object. For example:
// This article:
// https://stackoverflow.com/questions/21246818/how-to-get-the-base-url-in-javascript
var base_url = window.location.origin;
// "http://stackoverflow.com"
var host = window.location.host;
// stackoverflow.com
var pathArray = window.location.pathname.split( '/' );
// ["", "questions", "21246818", "how-to-get-the-base-url-in-javascript"]
In Chrome Dev Tools, you can simply enter window.location
in your console and it will return all of the available properties.
Further reading is available on this Stack Overflow thread
Solution 2:
One way is to use a script tag to import the variables you want to your views:
<script type="text/javascript">
window.base_url = <?php echo json_encode(base_url()); ?>;
</script>
Here, I wrapped the base_url with json_encode so that it'll automatically escape any characters to valid Javascript. I put base_url to the global Window so you can use it anywhere just by calling base_url, but make sure to put the script tag above any Javascript that calls it. With your given example:
...
$('#style_color').attr("href", base_url + "assets/css/themes/" + color_ + ".css");
Solution 3:
Base URL in JavaScript
Here is simple function for your project to get base URL in JavaScript.
// base url
function base_url() {
var pathparts = location.pathname.split('/');
if (location.host == 'localhost') {
var url = location.origin+'/'+pathparts[1].trim('/')+'/'; // http://localhost/myproject/
}else{
var url = location.origin; // http://stackoverflow.com
}
return url;
}
Solution 4:
var baseTags = document.getElementsByTagName("base");
var basePath = baseTags.length ?
baseTags[ 0 ].href.substr( location.origin.length, 999 ) :
"";
Solution 5:
This is done simply by doing this variable.
var base_url = '<?php echo base_url();?>'
This will have base url now. And now make a javascript function that will use this variable
function base_url(string){
return base_url + string;
}
And now this will always use the correct path.
var path = "assets/css/themes/" + color_ + ".css"
$('#style_color').attr("href", base_url(path) );