JavaScript object, call on page - javascript

I have one javascript file that houses all the functions for my website, stored it a large object, like this:
var Example = {
init : function(){
alert('init');
},
page_one : function(){
alert('this is page 1');
},
page_two : function(){
alert('this is page 2');
}
}
Now I like to open a simple script tag on the different pages, and on page1 do Example.page_one(); and on page2 do Example.page_two();
But this doesn't work. When I call those in the same file as where die Example object is made, then it works, but not if I include that file in a page, and call it from there.
The Example object does show up in the window object
Can someone help me?

Well, I fixed it myself. Stupid fault.
My code was like this:
<script defer src="js/scripts.js"></script>
<script>
AdminDashboard.notificationMessages();
AdminDashboard.setupMenu();
AdminDashboard.setupFileInput('#new_slideshow_image');
AdminDashboard.setupSlideCrop();
</script>
And the problem seemed to be with defer. The object did load, but after the script fired that called to it.
Thanks for the help!

If you will create example object in your page where you have included it, it will override example object. Try to use direct functions rather than this approach.

Related

Link + on(pagecontainershow) fail

I have a simple app done with jQuery Mobile, in some point I have this:
Start!
which loads a new HTML with a lot of jquery mobile pages:
<div data-role="page">
I have defined, in my external JS file, an global variable:
var startTimeQuestion;
And this method, which is inside my HTML (test_es.html):
<script>
$(document).on('pagecontainershow', function() {
console.log("Storing time..");
startTimeQuestion = new Date().getTime();
});
</script>
The problem is that when I click on the button it loads correctly the file but it seems like it don't load the JS or the function or I don't know, because when I'm going to use my startTimeQuestion variable it says UNDEFINED and it don't show in the console the 'Storing time..'. If a reload the page, it works fine.
I have tried to do an '$.(document).ready()' function for the first time I load the page but still not working. It looks like test_es.html it isn't loading my custom.css and my test.js file until I reload completely the page. So I supposed that the error is in how I call my test_es.html, it isn't this:
Start!
the correct way to do it?
Thanks.
Thanks to the comment before I found the solution, it was as simple as put the 'data-ajax' attribute to false this way:
Start!

Javascript element tag name undefined

So I'm not that great with Javascript so I'll put that forward right away. That being said, I've looked up as much as I could on this particular problem before asking, but the suggestions haven't solved my issues. I'm ultimately trying to pull all of the links from an iframe window on the same domain as the main page. Then I want to basically search that link array to match it with the current page to trigger a CSS modification to the html code (this part is not coded yet, FYI). So here is the part I have so far: Side note: The confirms are in there to debug the code and try to tell me where it's failing and what my queries are returning, they won't stay obviously when this is finished. I appreciate any advice that may help me fix this!
<script type="text/javascript">
// main is the iframe that I'm trying to search for a tags
document.getElementById("main").onload = function() {
confirm("test");
var main = document.getElementById("main");
var anchors = main.contentWindow.document.getElementsByTagName('a');
confirm(anchors[1]);
for (var i in anchors) {
confirm(anchors[i].getAttribute("href"));
}
};
</script>
I have created a plunker for you its working. I think its the placement of code in your file is causing the problem.
<iframe id="main" src="content_if.html"></iframe>
<script>
// main is the iframe that I'm trying to search for a tags
document.getElementById("main").onload = function() {
confirm("test");
var main = document.getElementById("main");
var anchors = main.contentWindow.document.getElementsByTagName('a');
confirm(anchors[1]);
for (var i in anchors) {
confirm(anchors[i].getAttribute("href"));
}
};
</script>
You should use jQuery to do this in a cross browser way. Include jQuery in page
<script src="https://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
and follow this post
There is a similar post about doing this and I agree with Mohamed-Yousef. If you can use jquery then you should do so!
$("#main").contents().find("a").each(function(element) {
// "each" will iterate through every a tag and inject them as the "element" argument
// visible in the scope of this anonymous function
});
EDIT:
You must include
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
above your code that references the $ variable. There are other ways to use jQuery but this is probably the easiest.

Why is JQuery not loading my script?

I have a script that I am using to share images. After the script (at the bottom) in the same js file I have the following:
$(document).ready(function() {
$(".shared").after('<div class="share-button"></div>');
});
new Share(".share-button", {});
For some reason the script does not work. But when I have the page up and enter the above script in, it loads and the div shows up.
Am I missing something here?
Looks like you're trying to instantiate a Share object that depends on the "share-button" elements existing, but those elements don't exist because they're added in $(document).ready(). Try this:
$(document).ready(function() {
$(".shared").after('<div class="share-button"></div>');
new Share(".share-button", {});
});
Note that the "new Share()" is inside the ready handler, after the "share-button" has been added to the page.

including a javascript file at the end of the file doesn't work for some functions

In my file, a have many dom elements and an external javascript file that has some functions to manage events. The problem is that when i include the functions.js file at the end of my main file:
<script src="functions.js"></script>
That works for some elements but not for others. So i move that at the top of my file, and now it works for some elements but not the other either.
It doesn't works means that i got such error in the web console:
ReferenceError: oneOfMyFunctions is not defined
What is the best place to put that include? Thanx in advance.
EDIT:
In my html file (the main file), i did this:
<script>
window.onload = function(){
// start calling your function eg. functions.j();
myFunction();
};
</script>
Still get the same issue.
You can put your JavaScript file anywhere in page. But you should use window.onload method to start execution of your code.
<script>
window.onload = function(){
// start calling your function eg. functions.j();
};
</script>
If you invoke the function before its loaded, it doesn't know what to do. There are two solutions to this:
Use the window.onload option (or jquery $(document).ready(function(){ ... });
make the function call after you load the scripts.

AJAX that calls a "parent" function

I've seen a few questions like the one I'll ask but nothing identical. I have two html files, main and today. What I want to do is load today.html via AJAX into a child div in main.html. Sometime after load, I would like to call a function that resides in main.html from today.html
Within Main I have this function:
function drawCircle (size){
alert('DRAWING');
}
This AJAX load:
$("#leftofad").ajax({
url: ":Today.html?r="+genRand(),
type: 'GET',
success: function(data) { },
error: function() { alert('Failed!'); },
});
And this div:
<div id="leftofad"></div>
In Today.html I have
<script type="text/javascript">
$(document).ready(function(){
drawCircle (100);
});
</script>
The load is going well but Today.html doesnt seem to recognize the drawCircle function. I've tried several precursors including this., window., and parent..
I understand that I can use the callback method of the AJAX loader in jQuery but I don't necessarily want to call drawCircle when the load is complete. I may want to wait a bit or do it as a result of an action from the user. Is it possible to reference these functions from an AJAX-loaded div? If not, can I use an alternative method like events and listeners to fire the drawCircle function?
Since you will be loading JS into your page, try calling the function directly?
(The ready function won't run as the main page is already loaded)
Main.html
<script type="text/javascript">
function drawCircle(size) { alert("DRAWING" + size); }
$(function() {
$("#leftofad").load("Today.html?r="+genRand(), function() {
alert('loaded successfully!');
});
});
</script>
<div id="leftofad"></div>
Today.html
<script type="text/javascript">
drawCircle(100);
</script>
If this doesn't work, I strongly suspect that JavaScript returned in an AJAX call is not executed.
In this case, refer to: How to execute javascript inside a script tag returned by an ajax response
$("#leftofad").ajax is not proper.
jQuery's $.ajax function does not use a selector.
What you can use is load:
$("#leftofad").load("Today.html?r="+genRand(), function(){
alert('loaded successfully!');
});
Everyone here has some good answers, but I believe there is a knowledge gap and we are missing some information. If I were you, I would add an alert to the script in the Today.html file right before the drawCirle. Then I would run this page using IE or Chrome dev tools or Firebug in Firefox. When the alert is displayed you can put a breakpoint in the javascript code. Then check your global scope to try and locate drawCirle...
Sorry this is not an exact answer, but with javascript files you need to use debugging tools for this.
while there isn't really a document.ready function for a div, there is a hack that works just as if so:
create your returning data as a full html page:
<html>
<head>
<script type='text/javascript'>
$(document).ready( function () {
do-this;
to-that;
....
});
</script>
</head>
<body>
<%
your possible vbscript
%>
the rest of stuff to be loaded into that div
</body>
</html>
Then, you can have as many cascading div loading from different page loading and .... rinse and repeat ... forever .... EXPERIMENT with different DOCTYPE to see the different results.
EDIT:
Then, of course, you load the original MAIN with
$('#thedivid').load('url-of-the-html-returning-page');
Which, in turn, can have the VERY SAME call in the returning page document.ready as, for example; $('#thedivid-inthereturningdata-html-page').load('url-of-the-html-of-the-child-process-for-whaterver); .... and so on.
Go ahead, PLAY AROUND and make wonderful ajax based applications ....

Categories