how to get html header's element - javascript

as i want to send the file names which is included in <head> section e.g. css & js file name including it's container folder to the server side via ajax.
please note that, in given example the css & js are located inside of files folder.
so how can i get the css & js file names including it's container
<html> <head>
<link rel="stylesheet" href="files/sample.css"/>
<script type="text/javascript" src="files/jquery.js"> </script>
</head>
Now i need to consider about other things too, sample.CSS
#myImage {
background: url('image/lucy.jpg');
/* also i need to get these image file name including details with location */
}

this is to get the resources names (stylesheets and scripts) in your head element :
function filterName(path){
path = path.split('/');
return path[path.length - 1];
}
var styleSheets = [];
$('head link[rel=stylesheet]').each(function(){
styleSheets.push(filterName($(this).attr('href'));
});
var scripts = [];
$('head script[src]').each(function(){
scripts.push(filterName($(this).attr('src'));
});
It's rather hard to actual parse these files and compute their fullpath. To get all the images, you may consider to traverse all of the dom elements and check if they have any background-image attached to them through css :
function filterBgImage(n){
var m = n.match(/url\(["'](.*?)["']\)/);
if(m && m.length == 2)
return m[1];
return n;
}
var imgs = [];
$('*')
.filter(function(){
var a = $(this).css('background-image');
return a != '' && a != 'none';
})
.each(function(){
imgs.push(filterBgImage($(this).css('background-image')));
});
The good thing about this approach is that you do not have to transform the relative path into full path, because jquery is doing that for you.

Im not sure what you want to do is possible from a web browser - but there are tools that will do it without -> http://www.httrack.com/html/overview.html

Related

Refreshing page with a new image [duplicate]

This question already has answers here:
Load Random Images from Directory
(5 answers)
Closed 7 years ago.
I currently have a stagnant image on my site:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="/stylesheets/normalize.css" media="all" rel="stylesheet" />
<link href="/stylesheets/master.css" media="all" rel="stylesheet" />
<script>
window.onload = function () {
var images = [],
i=1, indexImages = true,
prefix = '../image/',
extension = '.jpg';
while (indexImages) {
var a = new XMLHttpRequest(); a.open('GET', prefix+i+extension, false); a.send();
if (a.status != 404) { i += 1; images.push(prefix+i+extension); } else {
indexImages = false;
localStorage['backgroundIndex'] = !localStorage['backgroundIndex']?0:+localStorage['backgroundIndex']+2>images.length?0:+localStorage['backgroundIndex']+1;
document.body.style.backgroundImage = 'url(' + images[+localStorage['backgroundIndex']] + ')';
}
}
}
</script>
<style>
body {
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-color: black;
border-bottom: 8px solid #7D8A28;
}
</style>
</head>
<body>
<section id="card">
</section>
</body>
</html>
It's just that I want it to be a different image each time the page refreshes, so it auto changes to 2.jpg, 3.jpg, 10.jpg, whatever. (There are hundreds to choose from)
Could someone help me out with a solution? I'm not very good at this, and this is my first site.
Thanks.
I don't think CSS alone can do this, here's an answer:
Random
window.onload = function () {
var images = [
'image/1.png',
'image/2.png',
'image/3.png',
'image/4.png'
];
document.body.style.backgroundImage = 'url(' + images[Math.floor(Math.random()*images.length)] + ')';
}
This will load a random image every time you visit the page.
Specified Order
To load them in sequential order: First time image1, second time image2. The images don't need even have a number for this to work just fine. Do:
window.onload = function () {
var images = [
'image/A.png',
'image/B.png',
'image/C.png',
'image/D.png'
];
localStorage['backgroundIndex'] = !localStorage['backgroundIndex']?0:+localStorage['backgroundIndex']+2>images.length?0:+localStorage['backgroundIndex']+1;
document.body.style.backgroundImage = 'url(' + images[+localStorage['backgroundIndex']] + ')';
}
Generating the Array (ONLY IF YOUR IMAGES HAVE A NUMBER AT THE END)
This will automatically generate the array for you and you don't have to provide the amount of images
window.onload = function () {
var images = [],
i = 1,
prefix = 'image/',
extension = '.png',
max = 1000;
function index() {
var a = new XMLHttpRequest();
a.open('GET', prefix + i + extension, false);
a.send();
a.onreadystatechange = function () {
if (a.readyState === 4) {
if (a.status != 404) {
i += 1;
images.push(prefix + i + extension);
i < max ? index();
} else {}
localStorage['backgroundIndex'] = !localStorage['backgroundIndex'] ? 0 : +localStorage['backgroundIndex'] + 2 > images.length ? 0 : +localStorage['backgroundIndex'] + 1;
document.body.style.backgroundImage = 'url(' + images[+localStorage['backgroundIndex']] + ')';
}
};
}
index();
}
Most versatile solution
If you have PHP, this is probably the best solution in terms of working in many cases. But you really don't want to use PHP if you can avoid it. It will get all images in a directory to generate the array:
window.onload = function () {
var images = (JSON.parse("<?=scandir('../images')?>")||[]).filter(function (a) { return ['.', '..'].indexOf(a) < 0; });
document.body.style.backgroundImage = 'url(' + images[+localStorage['backgroundIndex']] + ')';
};
You can easily do it with JavaScript. You could define an array with all the images you have and then create a random number every time the page loads. Then use the random number to access the array's index to read the name of the image. Like so:
var images = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg", "image5.jpg"];
var randomNumber = Math.floor((Math.random() * images.length));
//images[randomNumber] contains your random image
Hope it helps.
Regards,
I see all these JS solutions but most likely you need a php one as I am sure you don't wanna put the names of hundreds of images in a file. So if you have some knowledge of programming in php then try this.
Generate a random number. Let's say it is 42
Read the file names one by one (http://php.net/manual/en/function.readdir.php)
Once you reach the 42nd file, pass it to the page.
You can either put the filename directly in the css or have a php page as a background image source which returns the images. Either case, the above steps will give you what you want.
The above works well if file names and types are different. However, if file names are numerical and all files are the same extension then just generating a number and just using it as the file name is slightly faster than the above method.
However, it is still faster than most JS solution. Remember that JS is on client side. That mean it will be executed after that page is loaded. With JS, files need to be as minimal as possible. Otherwise, the page would load and you wouldn't have a background until that request is returned. Considering all these delays, I wouldn't call JS efficient over PHP.
Although you can always make it nice and fade it in or something :)
No need for AJAX
Why you should use PHP
The added benefit of using PHP is we can make it so all you have to do is drop an image into a folder and it will automatically be added to the randomized list! Which is great for maintainability. You code it once, and leave it alone!
In my opinion, there is no added benefit to using AJAX. Any time you add an image, you would have to add it to your JS image array. However, I don't know your exact scenario.
Important
All the other solutions that mention PHP, so far, have failed to mention one very important part... the page you are working in must be parsed as a PHP file.
There are two ways to do so:
Parse html/htm page as php page via .htaccess (advanced)
Change your the page extension to '.php' (simple)
(My solution requires that your page is parsed as PHP)
Solution 1
I would use JavaScript to randomly select the image from a PHP generated list, then append CSS to apply the background image to the page before the window.onload event.
PHP with JavaScript Random
Append the following to page head:
<script type="text/javascript">
<?php
// Path to image can be a relative or absolute path. I recommend absolute.
// The following is my absolute path.
$img_dir_path = '/rand-img/images/';
// Get directory list. If using absolute, prepend $_SERVER['DOCUMENT_ROOT'] for php
$dir_listing = scandir($_SERVER['DOCUMENT_ROOT'].$img_dir_path, 1);
// array_diff() to remove '.' & '..' from front of $dir_listing array
$img_array = array_diff( $dir_listing, array('.', '..') );
?>
// JavaScript variables
var img_dir_path = '<?php echo $img_dir_path ?>';
var img_array = <?php echo json_encode($img_array) ?>;
var rand_index = Math.floor(Math.random() * img_array.length);
var img_path = img_dir_path + img_array[rand_index];
// no need to wait for window.onload if we append actual style tag
var css = 'body { background-image: url('+img_path+') !important; }',
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
</script>
Using PHP for random, will only work if the page is loaded without cache.
However, using JavaScript will randomize the image even if the actual page is cached.
Solution 2
In my experience, this solution will randomize the image the vast majority of the time. However, if the page is loaded via cache, the background image will not be re-randomized.
PHP Random
Append the following to page head:
<?php
// Path to image can be a relative or absolute path. I recommend absolute.
// The following is my absolute path.
$img_dir_path = '/rand-img/images/';
// Get directory list. If using absolute, prepend $_SERVER['DOCUMENT_ROOT'] for php
$dir_listing = scandir($_SERVER['DOCUMENT_ROOT'].$img_dir_path, 1);
// array_diff() to remove '.' & '..' from front of $dir_listing array
$img_array = array_diff( $dir_listing, array('.', '..') );
// Random number based off size of $img_array
$random_index = mt_rand(0, count($img_array)-1);
// Build image path
$image_path = $img_dir_path . $dir_listing[ $random_index ];
?>
<style type="text/css">
body {
background-image: url("<?php echo $image_path ?>");
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-color: black;
border-bottom: 8px solid #7D8A28;
}
</style>

Dynamically Creating bootstrap-sliders with jquery or javascript

I'm trying this with no success. For reference, the bootstrap slider is here : http://seiyria.github.io/bootstrap-slider/.
I'm not a javascript expert, either, so this might be very simple. The bootstrap-slider site has many examples of how to configure the sliders the way you want them. I'm going to have many sliders generated depending on how many objects are pulled from a JSON file or some other data storing method. It could be 2 or it could be 20.
I created a javascript function called createSlider that I've attempted to pass all of the information required at the bootstrap-slider site. I'm not getting any errors in my Chrome debugging area, but nothing is happening. All of the appropriate client-side sources are loading.
function createSlider (orgId) {
slidersList = document.getElementById('slidersList');
element = slidersList.createElement("div");
var sliderElement = element.createElement('input');
var sliderUnique= orgId.concat("Slider");
var sliderUniqueVal = orgId.concat("SliderVal");
sliderElement.setAttribute('id', charityId);
sliderElement.setAttribute('data-slider-id', sliderUnique);
sliderElement.setAttribute('type', 'text');
sliderElement.setAttribute('data-slider-min', '0');
sliderElement.setAttribute('data-slider-max', '100');
sliderElement.setAttribute('data-slider-step', '1');
sliderElement.setAttribute('data-slider-value', '50');
var span = element.createElement('span');
span.setAttribute('style', 'padding-left:5px;');
span.innerHTML =' ';
var innerSpan = span.createElement('span');
innerSpan.setAttribute('id', sliderUniqueVal);
innerSpan.innerHTML = '50';
sliderElement.slider({tooltip: 'hide'});
sliderElement.on("slide", function(slideEvt) {
innerSpan.innerHTML = text(slideEvt.value);
});
}
The slider() function is from the external site, and runs fine if I explicitly call it like the examples state to. Anyone know what's going wrong? Is there a better way to do this? Any ideas would be appreciated.
Note, in plain JavaScript, you can only use document.createElement and then append to another HTML element. You cannot call createElement directly against another HTML element.
I changed some of what you wrote from plain old JavaScript into JQuery, and now seems to work:
P.S. Didn't know where charityId came from, so just added it as another parameter into the function.
$(function() {
createSlider('o1','c1');
createSlider('o2','c2');
createSlider('o3','c3');
});
function createSlider (orgId, charityId) {
var slidersList = $('#slidersList');
var element = $("<div></div>").appendTo(slidersList);
var sliderElement = $("<input/>").appendTo(element);
var sliderUnique= orgId.concat("Slider");
var sliderUniqueVal = orgId.concat("SliderVal");
sliderElement.attr('id', charityId);
sliderElement.attr('data-slider-id', sliderUnique);
sliderElement.attr('type', 'text');
sliderElement.attr('data-slider-min', '0');
sliderElement.attr('data-slider-max', '100');
sliderElement.attr('data-slider-step', '1');
sliderElement.attr('data-slider-value', '50');
var span = $('<span></span>').appendTo(element);
span.attr('style', 'padding-left:5px;');
span.html(' ');
var innerSpan = $('<span></span>').appendTo(span);
innerSpan.attr('id', sliderUniqueVal);
innerSpan.html('50');
sliderElement.slider({tooltip: 'hide'});
sliderElement.on("slide", function(slideEvt) {
innerSpan.text(slideEvt.value);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script type='text/javascript' src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://seiyria.github.io/bootstrap-slider/stylesheets/bootstrap-slider.css">
<script type='text/javascript' src="http://seiyria.github.io/bootstrap-slider/javascripts/bootstrap-slider.js"></script>
<div id="slidersList"></div>

Best way to hide/don't load HTML-Parts based on configuration file?

What is the best way to hide HTML-Elements based on value in a configuration file?
Example:
A user acess a HTML-File. If the configuration file contains something like "expert = "false"", the Browser shouldn't load the expert-div.
The HTML and Javascript should run on local PC(shouldn't need a Web-Server)
You can do something like:
if(config.expert === false){
var expert = document.querySelectorAll('.expert'); // getting all elements with class expert
for(var elmt in expert){
elmt.style.display = 'none';
}
}
Make config js file and check it's values in your html page
config.js
var expert = false;
var somethingElse = true;
index.html
<script src="/config.js"></script>
<script>
if(!expert)
document.getElementById('expert').style.display = 'none';
if(!somethingElse)
document.getElementById('somethingElse').style.display = 'none';
...
</script>
just some basic idea.

only add script to head if doesn't exist

I want to add additional scripts and styles to my site when a specific div is loaded.
I start out by defining a path to either a script or stylesheet and then create an element. Hereafter I append the element to the head tag in HTML.
But I would like a way to see if the script or stylesheet already has been append before I append it again. It would be stupid to append an already existing script or stylesheet.
Q: How do I use javascript to check wether or not a script already exists in the head tag, and then append the element if not?
EDIT
I have made a function based on the answer from #KernelPanik. It doesn't work yet but hopefully it will. The function is currently in question: my script appending function doesn't work
If you can use jquery, this code is good
function appendScript(filepath) {
if ($('head script[src="' + filepath + '"]').length > 0)
return;
var ele = document.createElement('script');
ele.setAttribute("type", "text/javascript");
ele.setAttribute("src", filepath);
$('head').append(ele);
}
function appendStyle(filepath) {
if ($('head link[href="' + filepath + '"]').length > 0)
return;
var ele = document.createElement('link');
ele.setAttribute("type", "text/css");
ele.setAttribute("rel", "Stylesheet");
ele.setAttribute("href", filepath);
$('head').append(ele);
}
In your code write
appendScript('/Scripts/myScript.js');
appendStyle('/Content/myStyle.css');
var lib = '/public/js/lib.js';
if (!isLoadedScript(lib)) {
loadScript(lib);
}
// Detect if library loaded
function isLoadedScript(lib) {
return document.querySelectorAll('[src="' + lib + '"]').length > 0
}
// Load library
function loadScript(lib) {
var script = document.createElement('script');
script.setAttribute('src', lib);
document.getElementsByTagName('head')[0].appendChild(script);
return script;
}
You can use the DOM getElementsByTagName("script") to get all of the <script> tags in the document. Then you can check the src urls of each script tag returned, for the url of the script(s) that you have added to the head section. Likewise, you can do something similar for the style sheets by replacing the search of "script" with "style".
For example, if the url of the script appended to the <head> section is header_url.html
var x = document.getElementsByTagName("script");
var header_already_added = false;
for (var i=0; i< x.length; i++){
if (x[i].src == "header_url.html"){
// ... do not add header again
header_already_added = true;
}
}
if (header_already_added == false){
// add header if not already added
}
Likewise, if the url of the style appended to the <head> section is header_style.css
var x = document.getElementsByTagName("style");
var header_already_added = false;
for (var i=0; i< x.length; i++){
if (x[i].src == "header_style.css"){
// ... do not add header again
header_already_added = true;
}
}
if (header_already_added == false){
// add header if not already added
}
A similar question was also asked here: Check if Javascript script exists on page
I used Jack Lee's solution. It was easy to implement and quickly versitile with just about any type file.... I didn't expand on anything ...I actually probably stupefied it a bit... just wanted to list what I did in case it helps someone else...
var lib_jq = '//pathtofile/jquery.js';
var lib_bs = '//pathtofile/bootstrap.min.3.5.js';
var lib_cs = '//pathtofile.css';
///checks files with the SRC attribute
function isLoadedScript(lib) {
return document.querySelectorAll('[src="' + lib + '"]').length > 0
}
///checks files with the HREF attribute
function isLoadedCss(lib) {
return document.querySelectorAll('[href="' + lib + '"]').length > 0
}
///loads the script.js files
function loadScript(link) {
document.write('<scr' + 'ipt type="text/javascript" src="'+link+'"></scr' + 'ipt>');
}
///loads the style.css files
function loadCss(link) {
document.write('<link rel="stylesheet" href="'+link+'">');
}
/// run funtion; if no file is listed, then it runs the function to grab the URL listed. ///Run a seperate one for each file you wish to check.
if (!isLoadedScript(lib_jq)) { loadScript(lib_jq); }
if (!isLoadedScript(lib_bs)) { loadScript(lib_bs); }
if (!isLoadedCss(lib_cs)) { loadCss(lib_cs); }
I know there is always a "better" and more "elegant" solution, but for us beginiers, we got to get it working before we can start to understand it...
Another way with a function helper like below
function isScriptAlreadyPresent(url) {
var scripts = Array.prototype.slice.call(document.scripts);
return scripts.some(function(el) {
return el.src && el.src != undefined && el.src == url;
});
}
isScriptAlreadyPresent('http://your_script_url.tld/your_lib.js');
It uses Array.prototype.some function. You may need a es5-shim if your are in browsers not supporting ES5 (IE7 and IE8...)
maybe headjs can help you.
or maybe you can add onload attribute in the script tag.
my english is a little poor,so maybe i'm misunderstand your question.
if(ie){
js.onreadystatechange = function(){
if(js.readyState == 'complete'){
callback(js);
}
}
else{
js.onload = function(){
callback(js);
}
You can try calling some function, object, variable from that js script file, if it finds it then it exists, if not, you need to insert that js script file.

Manipulate DOM element to extract some nodes and remove others

I need to manipulate HTML code. Specifically, the user should be able to copy/paste the code to create an AddThis button in a textarea, and I want to manipulate the pasted code.
A typical AddThis button looks like this :
<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style ">
<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>
<a class="addthis_button_tweet"></a>
<a class="addthis_counter addthis_pill_style"></a>
</div>
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-123456798"></script>
<!-- AddThis Button END -->
It consists of start and end comments, a div and/or some links, followed by 2 scripts: a config setting, and a call to their library.
The problem is, we need to call this many times on the page ; so, if I just put this every time I want to place an AddThis button, I fear that at least some browsers will have weird behavior, if it works at all.
So, I want to extract the config setting and the lib call, so I can call them just once, and extract the buttons config, so I can place it as many times as I want on the page.
I have already done that :
var codeAT = $(this).val();
if (codeAT.indexOf("AddThis Button BEGIN") >= 0) {
codeAT = codeAT.replace("<", "<");
codeAT = codeAT.replace(">", ">");
codeAT = $(codeAT);
// extract the call to the config var and the lib
var scriptConfig = "";
var scriptSRC = "";
codeAT.each(function() {
if ($(this).attr("nodeName") == "SCRIPT") {
if ($(this).attr("src") && $(this).attr("src") != "") {
scriptSRC = $(this).attr("src");
} else {
scriptConfig = $(this).text();
}
}
});
// extract the addthis identifier
scriptSRC = scriptSRC.split("=")[1];
}
Now, I can use the vars scriptConfig (with var addthis_config = {"data_track_clickback":true};) and scriptSRC (with ra-123456789), and they have the correct values.
What I want now, is the original code (between the two comments), without the comments, and without the script tags.
To remove the tags, I tried to use codeAT.remove($(this)), but it crashes (something about c.replace not being a function).
To get the code back, I tried codeAT.html(), but it gets only the tags.
Instead of .each() I'd do:
//remove <script> tags and get required info
var scriptSRC = $('script[src]', codeAT).remove().attr('src');
var scriptConfig = $('script:not([src])', codeAT).remove().text();
//get the code (as string)
var code = $('<div>').append(codeAT).remove().html();

Categories