I am developing a new application where different pages has different DOM element like Map page has some map specific element and Message page has message specific. To reduce the number of requests, I am combining all scripts to one file and put into footer.
But the problem is that when I am on Map Page, getting error for the missing elements that are only exists on Message page, I believe I am missing something very easy but I could not figure it out.
You can use try and catch if you don't want your script stops.
i.e.
try{
var test = document.getElementById("someelementthatdontexsist");
alert(test.innerHTML);
}
catch(err){};
so as Esko suggested you need to use "if" to check if you are on right page to run appropriate code.
sample:
var PageName = document.getElementsByTagName('body');
document.getElementById("check_button").addEventListener('click', function () {
if (PageName[0].getAttribute('id') == "map_page") {
//do map_page things
document.getElementById("page_name").innerText = PageName[0].getAttribute('id');
}
if (PageName[0].getAttribute('id') == "message_page") {
//do message_page things
document.getElementById("page_name").innerText = PageName[0].getAttribute('id');
}
});
<body id="map_page">
<button id="check_button">Check page</button>
<span id="page_name">test
</span>
</body>
Related
Basically I'm trying to build a functionality in which I only really edit my index.php, I got a lot of other php files with just a form in them or just a few lines of text.
What I want to achieve is to load these other files in the contentwrapper of my index.php.
I have been successfull on doing this with an iframe and with a html <object>.
The problem with these though is that first of all they load an all new #document in the DOM, and also my webpage has no set height so height: 100% won't work on those and I would get these ugly scrollbars and stuff.
after searching a lot on SO today I found a few interesting solutions which I combined, this is what I'm trying now:
<script type="text/javascript" href="js/csi.min.js"></script>
<script type="text/javascript">
function load_content(target){
document.getElementById('contentwrapper').innerHTML='<div data-include="' + target + '" ></div>';
return false;
}
</script>
now you may question what data-include is, this is a very nice workaround I found on SO.
THIS is what it does, it basically calls a .js file that replaces the containing element with the data that is in the file (target in the above example)
I call this functionality like this:
Update profile
It works as far as adding this to the DOM:
<div id="contentwrapper">
<div data-include="update.php" ></div>
</div>
but besides that it does nothing, I think that it doesn't call the .js file for the data-include attribute. But I can't find a solution for this nowhere.
(BTW: the data-include attribute does work if I put it in a tag manually without javascript)
I Hope I didn't overexplain the situation, and I thank everyone that tries to help in advance!
The csi.js script is only run once after the page is loaded. It just goes over all the elements with the data-include attribute and runs the fragment function.
<script type="text/javascript">
function fragment(el, url) {
var localTest = /^(?:file):/,
xmlhttp = new XMLHttpRequest(),
status = 0;
xmlhttp.onreadystatechange = function() {
/* if we are on a local protocol, and we have response text, we'll assume
* things were sucessful */
if (xmlhttp.readyState == 4) {
status = xmlhttp.status;
}
if (localTest.test(location.href) && xmlhttp.responseText) {
status = 200;
}
if (xmlhttp.readyState == 4 && status == 200) {
el.outerHTML = xmlhttp.responseText;
}
}
try {
xmlhttp.open("GET", url, true);
xmlhttp.send();
} catch(err) {
/* todo catch error */
}
}
function load_content(target){
fragment(document.getElementById('contentwrapper'), target);
return false;
}
</script>
Then call it like this:
Update profile
So, the only thing you need is to call this function for the new created element. Pass the DOM element and the url to this function and it will take care of loading the contents of the requested resource in the corresponding element.
May we assume that you followed this advise from the repository: The only caveat is Chrome, which restricts access to local files via AJAX. To resolve this, simply add --allow-file-access-from-files to your Chrome runtime.
If you didn't, and you're using Chrome, then this stands out to me, and you didn't indicate that you'd corrected the security block that Chrome puts in place.
The csi.js only runs on window.onload.
Try
<a href="#" onclick="function() {load_content('update.php'); window.onload(); }">
Update profile</a>
I am trying to fire a script when the contents of a div are altered, specifically when a div receives the next set of results from a js loaded paginator.
I have this:
<script script type="text/javascript" language="javascript">
document.addEventListener("DOMCharacterDataModified", ssdOnloadEvents, false);
function ssdOnloadEvents (evt) {
var jsInitChecktimer = setInterval (checkForJS_Finish, 111);
function checkForJS_Finish () {
if ( document.querySelector ("#tester")
) {
clearInterval (jsInitChecktimer);
//do the actual work
var reqs = document.getElementById('requests');
var reqVal = reqs.get('value');
var buttons = $$('.clicker');
Array.each(buttons, function(va, index){
alert(va.get('value'));
});
}
}
}
</script>
This works well when the doc loads (as the results take a few seconds to arrive) but I need to narrow this down to the actual div contents, so other changes on the page do not fire the events.
I have tried:
var textNode = document.getElementById("sitepage_content_content");
textNode.addEventListener("DOMCharacterDataModified", function(evt) {
alert("Text changed");
}, false);
But the above does not return anything.
Can what I am trying to do be done in this way? If yes where am I going wrong?
Using Social Engine (Zend) framework with MooTools.
I did this in the end with a little cheat :-(
There is a google map loading on the page that sets markers to match the location of the results. So I added my events to the end this code namely: function setMarker() {}.
I will not mark this as the correct answer as it is not really an answer to my question, but rather a solution to my problem, which is localised to the Social engine framework.
I will add a Social engine tag to my original question in the hope it may help someone else in the future.
Thanks guys.
I'm trying to add a function to a toolbar Chrome extension I've made. What I'd like it to do is once a navigate to a particular page I'd like be able to push a button on the tool bar and have it "click" all of the links on that page containing harvest.game?user=123456 with 123456 being a different number for all of the links. It could be using jquery or javascript. The only catch is that the script will need to be inserted as an element to the head of the page as cross domain scripting is not allowed so no external references to a js file. I can handle the adding of the element but, I'm having no luck figuring out the actual function.
The elements containing the links all look like this:
<div class="friendWrap linkPanel">
<h5>Christine...</h5>
<div class="friend-icon">
<img src="https://graph.facebook.com/100001726475148/picture"></div>
<div class="levelBlock friend-info">
<p>level</p>
<h3 class="level">8</h3></div>
Harvest
<a class="boxLink" href="profile.game?user_id=701240"><span></span></a></div>
Something like this (I know this is a mess and doesn't work)? OR maybe something BETTER using jquery?
var rlr=1;
function harvestall(){var frt,rm,r,rld,tag,rl;
var frt=1000;
r=document.getElementsByClassName("friendWrap linkPanel");
rl=r.length;
rld=rl-rlr;
if(rld>=0){tag=r[rld].getElementsByTagName('a');
if (rl>=1 {rlr++;harvestall();}
else if (rl>=1) {tag[1].onclick();do something??? ;}
}
Something like this should work
$("a[href*='harvest.game?user=']").trigger("click");
// Using jQuery, wait for DOMReady ...
$(function harvestLinks() {
// Only create regexp once ...
var reURL = /harvest.game\?user=/,
// Create a ref variable for harvest links ...
// Use 'links' later without querying the DOM again.
links = $("a").filter(
function() {
// Only click on links matching the harvest URL ...
return this.href && reURL.test(this.href);
}
).click();
});
i am trying to call a external HTML page to be displayed on website based on javascript conditions.
The code is like this
<script language="JavaScript" src="http://j.maxmind.com/app/country.js"></script>
<script type="text/javascript">
var country = geoip_country_code();
if (country == "US")
{
document.write("http://www.mywebsite.com/1.html");
}
else if (country == "GB")
{
document.write("<a href='#'><img src='http://www.image2.com' ><a/>");
}
else
{
document.write("<a href='#'><img src='http://www.image3.com' ><a/>");
}
</script>
Now, instead of showing the content of HTML page to US visitors, it just display "http://www.mywebsite.com/1.html" as plain text.
I am missing a function to call external HTML. Can someone help? Thanks
Do you mean the <iframe> element?
document.write('<iframe src="http://www.mywebsite.com/1.html"></iframe>');
Since <iframe> cannot resize itself to match the size of its content, be sure to give it a width/height attribute or style (if you know the actual size of content).
Spitting the text of a URL into a page doesn't magically grab the contents of that page. This type of activity usually happens on the SERVER where your server will fetch the content from another page and serve it up as part of YOUR page. JavaScript is the wrong tool for this job.
this kind of thing is really better to do server-side with stuff like php but here's a function I use in a lot of my commercial jobs. Again, I don't condone the use of this function for loading entire pages, but it's a really handy one to have in your toolbox. If anyone says you have to use JQuery to do this, kick them for me. ^_^
function fetchHTML(url)
{
if( 'undefined' == typeof(url) ) return false;
if( document.all ){
p = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
p = new XMLHttpRequest();
}
rnd = Math.random().toString().substring(3);
if( url.indexOf('?') > -1 )
{
url+='&rnd='+rnd;
}
else
{
url+='?rnd='+rnd;
}
p.open("GET",url,false);
p.send(null);
return p.responseText;
}
well, you are giving a string to document.write() function, and that's why it is displaying the string that it was supposed to display. If you want to display content of some other page you have two choices either you can use an <iframe> or use ajax.
I'm writing some code that will get executed before the DOM loads, basically, using Modernizr to get scripts. Now my issue is that I want to show a loading animation if the DOM loads and the scripts are still loading.
Modernizr is executed in the head. If I put the code to use document.getElementById in the head also, error is thrown because the DOM hasn't loaded. Now I have no idea how to solve this.
Here is the code I have so far:
<head>
<script>
var FileManager = {
IsLoading = false;
LoadRequiredFiles: function (config) {
config = config || {};
this.OnLoading = config.onLoadingCallback;
this.OnComplete = config.onCompleteCallback;
this.IsLoading = true;
if (this.OnLoading) {
this.OnLoading();
}
var self = this;
Modernizr.load([{
load: '/jquery.min.js',
complete: function () {
if (self.OnComplete) {
self.OnComplete();
}
self.IsLoading = true;
}
},
]);
}
};
var globalLoadingId = 'globalLoader';
FileManager.LoadRequiredFiles({
onLoadingCallback: function () {
document.getElementById(globalLoadingId).style.display = 'block';
},
onCompleteCallback: function () {
document.getElementById(globalLoadingId).style.display = 'none';
}
});
</script>
I used to execute this code below the <body> tag, and it worked. Now I moved it into the <head>. So I used to pass 2 callbacks to it. Now I'd rather attach events to it and handle them in the body (assuming thats where the DOM is loaded).
What I'd like to do:
<head>
<script>
FileManager.LoadRequiredFiles();
</script>
</head>
<body>
<script>
//Bind the event, not sure if this is even possible in javascript.
FileManager.OnCompleted += fileManagerCompleted;
fileManagerCompleted()
{
document.getElementById(globalLoadingId).style.display = 'none';
}
if(FileManager.IsLoading)
{
document.getElementById(globalLoadingId).style.display = 'block';
}
</script>
</body>
The page is your canvas for display. You can't show anything before it loads. It sounds more like you want a very small page to load (quickly) where you could display your progress and then your code could dynamically load/display the rest of the page with ajax calls and javascript showing progress as it goes. That's the only way to get out in front of the rest of the page load that I know of.
The only entirely reliable way to run a script that manipulates the DOM is to use the body onload event. (window.onload is popular, but not quite 100% reliable.)
There are some browsers that implement a onDocumentReady event that can be kind-of-sort-of faked in IE, but I don't recommend its use.
Using getElementById will not, by itself, throw an error if used in the head. You might be causing an error because you aren't checking the returned value, which will be null if an element with the specified id wasn't found, e.g.
var el = document.getElementById('foo');
if (el) {
// do somethig with el
} else {
// el wasn't found
}
Your problem is how to display the image only if the scripts are still loading and the page is visible. The simple answer is don't use client-side script loading, do it at the server. :-)
If you want to persist with script loading, add a class to the loading image, say "hideOnLoad". Have a callback from the last script load that sets the rule to "display: none" (just create and add style sheet with that one rule using script).
Now you just include the loading image as the first element in the body with a class of "hideOnLoad", knowing that when scripts have finished loading they will hide the image regardless of whether it (or any other element with the same class) existed at the time or not.