I feel there is such an easy answer to this, but my google-fu is failing me. What I currently have are several links that once clicked, change the HTML content in a DIV.
<a href="#new" onclick="document.getElementById('body').innerHTML
= '<p>NEW</p>';">NEW!</a>
But I want to be able to link to this content. Is there anyway to link to this by going to a URL such as www.blahblah.com/index.html#new so it auto-loads the new HTML code?
Forgive me if I'm an idiot... I'm fairly new to javascript.
You can use window.location.hash to see what the hash is on the URL and show the correct DIV based on that. Assuming all your divs are on the page, once you know the div you want to show you would do something like this:
document.getElementById(idOfDivToShow).style.display='block';
Small example:
<html>
<head>
<script type="text/javascript">
function loadDiv() {
if(window.location.hash == '#div1')
document.getElementById('div1').style.display = "block";
else if(window.location.hash == '#div2')
document.getElementById('div2').style.display = "block";
}
</script>
</head>
<body onload="loadDiv()">
<div style="display:none" id="div1">div1</div>
<div style="display:none" id="div2">div2</div>
</body>
</html>
If you use jQuery, Mootools, or Prototype you could use history.js which allows you to set up states with specific content depending on the hash.
Related
Imagine I have following html with many items:
<html><body>
<img src=http://host.com/pic1.jpg>
<img src=http://host.com/pic1.jpg>
<img src=http://host.com/pic1.jpg>
</html></body>
Site owner adds some script to the page without other modifications:
<script>
var some_super_function = ... // what can i put here?
some_super_function('host.com','ghost.com');
</script>
and during loading of this html, host.com is replaced with hgost.com, so images are loaded from another server, as if the urls were:
<html><body>
<img src=http://ghost.com/pic1.jpg>
<img src=http://ghost.com/pic1.jpg>
<img src=http://ghost.com/pic1.jpg>
</html></body>
I guess selecting $('img') and tuning .attr() is not a good idea, because this may work only after page has loaded and I don't want the browser to reference host.com at all.
I guess angularJS is doing something like that, isn't it?
Is this possible?
Thanks.
Tested in firefox:
<body>
<script>
document.write('<!--');
var body = null;
setTimeout(function() {
body = document.body.innerHTML
console.log(body)
}, 0)
</script>
Now you can extract page contents from body variable, do with them whatever you wish and then put into page (with jQuery('body').html(...) for example).
I don't know if it would work if there were comments in the page. There are other ways to stop page from loading. Something like document.write('<script>');. I also tried document.write('<style>'); in firefox, also works.
You can use angular ng-src and {{}} syntax to bind your img domain:
var superFn = function(){ $('img').attr('src','ghost'); }
superFn();
angular.module('myApp',[]).controller('myCtrl',myCtrl);
function myCtrl($scope){
$scope.domain = "a3.mzstatic.com";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<img ng-src="http://{{domain}}/us/r30/Purple69/v4/d5/9e/6d/d59e6dfa-2176-7bc1-20a8-d3a1316c7bb8/icon100x100.png" >
<img ng-src="http://{{domain}}/us/r30/Purple69/v4/d5/9e/6d/d59e6dfa-2176-7bc1-20a8-d3a1316c7bb8/icon100x100.png" >
<img ng-src="http://{{domain}}/us/r30/Purple69/v4/d5/9e/6d/d59e6dfa-2176-7bc1-20a8-d3a1316c7bb8/icon100x100.png" >
</div>
I guess I know what you need. You need to define a base, and manipulate it to serve your needs. Like:
<script type="text/javascript">
document.write("<base href='http://yourimageurl.com/' />");
</script>
You must use this code before body tag.
How can you set your image urls? This way you have to mirror file names in order to make it work. And only relative url's will work.
Can you use CSS to hide the images initially, wait until the document is ready, then change the images and display them in JS?
CSS
img {
display: hide;
}
JS
$(document).ready( function() {
// ... selecting $('img') and tuning .attr() as mentioned in question
// Show the images
$('img').show();
}
I guess angularJS is doing something like that, isn't it?
No, angular use ng-src but for that you need to change the html
Is this possible?
I don't think it's possible to do reliably, from the client side without changing the html. One issue is when the document is loading, the browser will fetch images as soon as browser hits the image src element, even if you can execute a script before that, since document is not loaded script does not have access to the element.
May be you could kick off a window.setInterval function to check for elements and change sources, still it's not going to be a good approach.
In pure Js
you can do :
<!DOCTYPE html>
<html>
<head>
<script>
some_super_function = function(orig, alt)
{
Array.prototype.forEach.call(document.querySelectorAll("img[src*='"+orig+"']"), function(img)
{
var src = img.src;
var host = src.replace(/^(.*\/\/[^\/?#]*).*$/,"$1");
img.src = "http://"+src.replace(host, alt);
});
}
</script>
</head>
<body>
<img id="ol" src="http://www.intertools.net/lib/media/img/selector.png">
<img id="io" src="http://www.intertools.net/lib/media/img/selector.png">
<script>
// callable anywhere
some_super_function("www.intertools.net", "en.intertools.net");
</script>
</body>
</html>
To avoid caching, you can even use (assuming you are using html5)
<html manifest="manifest.appcache">
If I not mistaken is it your requirement.
var some_super_function = function(old_host,new_host)
{
$('img').each( function() {
var newSrc;
newSrc = $(this).attr('src').replace(old_host, new_host);
$(this).attr('src',newSrc);
console.log($(this).attr('src'));
});
}
some_super_function('host.com','ghost.com');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<img src="http://host.com/pic1.jpg" alt="pic1"/><br/>
<img src="http://host.com/pic2.jpg" alt="pic2"/><br/>
<img src="http://host.com/pic3.jpg" alt="pic3"/><br/>
JsFiddle Demo
I'm looking for a way that I can search an entire HTML document for a specific word and then swap each instance of that word with an image.
The problem I have is that I don't know what content is there because it is a dynamic page where the content is edited elsewhere and the site just pulls it in so referencing classes and ids is difficult.
I created a simple example with text that could resemble the content but the problem I have is my script will replace the whole document (I believe because of .html?) and I just want it to replace that specific piece of text.
<p>hi</p>
<p>j</p>
var x = $('body:contains("hi")');
x.html('<img src="/Content/by_car.jpg" />');
Could someone point me in the right direction?
Thanks in advance
You need to replace the original html like so x.html(x.html().replace('hi', '<img src="/Content/by_car.jpg" />'));
Also, this will be bad if, for example you will have <p class="hiblo">hi</p>. In this canse it will replace hi in hiblo and hi inside p tag thus ruining your markup.
Generally you can use some kind of regex but it's still not recommended to parse html with regex.
Here is working code.
This code also makes sure that script and style tags don't get replaced otherwise page logic will be broken. So it is taken care of as well.
<html>
<head>
<script type="text/javascript" src="jquery-1.11.3.min.js" > </script>
<style></style>
</head>
<body>
<h1>hi</h1>
<div>hi</div>
<input type="button" onclick="return replaceWithImage()" value="replace with image"/>
<script type="text/javascript">
function replaceWithImage() {
var x = $('body').find(':contains("hi")');
x.each(function(){
if($(this).prop('tagName') != 'SCRIPT' && $(this).prop('tagName') != 'STYLE')
$(this).replaceWith('<img src="/Content/by_car.jpg" />');
});
return false;
}
</script>
</body>
</html>
I have integrated a Twitter feed into a website, if the end location (presumably http://twitter.com/something) cannot be reached, the feed does not display. This is ideal, however I have a title div placed directly above the feed which remains visible regardless of whether the feed is displayed on the page or not.
Is it possible to prevent the div (#title) from displaying if a URL cannot be reached? I've found JavaScript snippets which look to hide a div based on the URL of the file being viewed, but this doesn't seem to work in my situation.
HTML:
<div id="title">
<h3>Latest Tweets</h3>
</div>
<div id="twitter_update_list">
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js">
</script>
<script type="text/javascript" src="http://api.twitter.com/1/statuses/user_timeline/SW_Trains.json?callback=twitterCallback2&count=3">
</script>
</div>
Many thanks in advance. I understand that this may not be possible with JS.
Use this.
<div id="title" style="display:none;">
<h3>Latest Tweets</h3>
</div>
<div id="twitter_update_list">
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js">
</script>
<script type="text/javascript" src="http://api.twitter.com/1/statuses/user_timeline/SW_Trains.json?callback=twitterCallback2&count=3">
</script>
</div>
<script type="text/javascript">
window.onload = function(){
var tdata = jQuery('#twitter_update_list').html().length;
if(tdata > 0)
{
jQuery('#title').css('display','block');
}
else
{
jQuery('#title').css('display','none');
}
}
</script>
May be it helps to you.
Maybe sth like
var divContent = document.getElementById('twitter_update_list');
if (NOT divContent) {
//no content detected
document.getElementById('title').style.visibility = 'hidden';
}
This is untested and I don't know if it works. You will have to create a function which will be executed when the page has completely loaded. Maybe sth like:
window.onload = function(){
// your code...
};
After load make a function that tests the content of the div that would hold the content. If is empty just hide whatever you need to hide.
I would like some help displaying contents (to different pages) within one HTML page using JavaScript.
This is a sample of what I have found so far: http://www.swan10.nl/stuff/test.htm however instead of displaying "FAQ question #blabla" in the box every time a link is clicked, I would like to display words and images like a normal content. Is there a way to do this?
I tried removing the CreateDiv function and replacing it with HTML codes but it doesn't work.
Thank you in advance :)
Umm, well you would need to use AJAX to pull the data into the page and display it in whatever method you choose. If you want to use a framework look into JQuery. It has nice AJAX functions. Otherwise read HERE
After re-reading your post I think you might just want to choose which div is displayed on a form at one time. This you can achieve by placing all of your divs in the same container. Then toggle their display css property.
Using jQuery it's as simple as
$('#divname').load('/path/to/file.html');
Note that the result should probably not include <html> and <head> tags (although you don't seem like you care about well formed HTML code).
I should probably also mention that you shouldn't make the client load content for you, that's what server side code is for.
Personally I would use the innerHTML property on one of your elements. It will allow you to add markup to that element. Check it out here: http://www.w3schools.com/jsref/prop_html_innerhtml.asp
<html>
<head>
<title>Multiple DIV</title>
<style type="text/css">
DIV#db {
border : 1px solid blue;
width : 400px;
height : 400px;
}
</style>
<script type="text/javascript">
var Content = new Array();
Content[0] = '<i>test1</i>';
Content[1] = '<b>test2</b><br><img src =http://www.w3schools.com/images/w3schoolslogo.gif>';
Content[2] = '<u>test3</u>';
Content[3] = '<s>test4</s>';
function Toggle(IDS) {
document.getElementById('db').innerHTML = Content[IDS];
}
</script>
</head>
<body onLoad="Toggle(0,10)">
FAQ #1
FAQ #2
FAQ #3
FAQ #4
<p />
<div id="db"></div>
</body>
</html>
I updated it to work all javascripty with the innerHTML
It is possible not to show html page in user browser until some JavaScript(built-in or in separate file) will be loaded and executed(for page DOM manipulation)?
The easiest thing to do is to set the css variable
display: none;
to the whole page.
then when everything is loaded you can set the display to
display: block; // or something else that suits.
If you make sure that piece of CSS is loaded at the very start of your document it will be active before any html is shown.
if you use a javascript library like jQuery you'll have access to the $(document).ready() function, and can implement a switch over like this:
<html>
<head>
<title>test</title>
<style type="text/css">
body > div {
display: none;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$('body > div').css('display', 'block');
});
</head>
<body>
<div>
This will initially be hidden.
</div>
</body>
</html>
Not in the classical way you'd distribute a page. Browsers will (usually) start to display chunks of the base HTML file as it arrives.
Of course, you could simulate this by generating all the HTML on the fly from some included Javascript file. But that doesn't sound like a good plan as it will degrade horribly for people without JS enabled, or if you have a minor bug in your script. A better option might be to style the body tag to display: none and restyle it from the script to make certain parts visible again.
What is it you're actually trying to achieve? It sounds like there's likely to be a better way to do this...
Place the content of HTML page in a DIV, make its diplay none and on load of body diplay it.
<script type="text/javascript">
function showContent() {
var divBody=document.getElementById('divBody');
divBody.style.display= 'block';
}
</script>
<body onload="showContent()">
<div id="divBody" style="display: none;">
<--HTML of the page-->
</div>
</body>
Examples of what you might want to do:
Facebook's "BigPipe": http://www.facebook.com/notes/facebook-engineering/bigpipe-pipelining-web-pages-for-high-performance/389414033919
This method allows you to load JS first then ASYNC+inject all DOM content.
GMail
Zimbra (open-source web app similar to MS Outlook/Exchange)
My understanding is that you want to run some javascript code before you load the page. In the js file you write your init function and add the eventlistener to the window on "load" event. This will ensure that the init code gets executed first and then you can start displaying the HTML content.
var Yourdomain = {};
YourDomain.initPage = function(){
/* Your init code goes here*/
}
window.addEventListener("load", YourDomain.initPage, false);
All You really need to do is give your element an ID or CLASS and use the dislay: none; property. When your ready to show it just delete it.
CSS:
#div_1 {
display: none;
}
HTML:
<div id="div_1">
<p>This will be the hidden DIV element until you choose to display it.</p>
<p id="js_1"></p>
<script>
var x = "Some Test ";
var y = "Javascript";
document.getElementById("js_1").innerHTML = x + y;
</script>
</div>