I have some content loaded in my page using ajax. I want to run a JS function when some anchors are clicked. These anchors belongs to the code loaded using ajax. Both the ajax request and the JS function are located in a separate JS file, inside a jQuery(document).ready(function() {.
I have a few dozens functions in this JS file, and they're running fine, but this specific function is the only one called by code retrieved using ajax, and it is not working. My code:
html main file:
<!-- code -->
<div id="ajaxContentGoesHere">
<!-- content inserted here by ajax function -->
<td>Editar</td>
</div>
<script src="/js/myJS.js"></script>
</body>
/js/myJS.js file:
jQuery(document).ready(function() {
/*some other functions here*/
$("[id^='aLancamentoEdit']").click(function(){
console.log(1);
}
});
I tried to put the $("[id^='aLancamentoEdit']").click(function(){ inside the html main file, in a tag after the /js/myJS.js call. Didn't work.
Also tried to change the selector to match my anchor class (I declared a class for this). No success either. Finally tried also to put a name in the function and call it on onclick="" inside the anchor. Failed again.
What am I doing wrong?
Since the element by id starting with 'aLancamentoEdit' is dynamically added by ajax, you need to bind click handler to parent:
$('#ajaxContentGoesHere').on('click', "[id^='aLancamentoEdit']", function() {
console.log(1);
});
Use .on() for dynamic element events (ajax content in your case). Try:
jQuery(document).ready(function() {
/*some other functions here*/
$("#ajaxContentGoesHere").on("click","[id^='aLancamentoEdit']",function(){
console.log(1);
}
});
Related
I'm trying to simply detect clicking an A link to display an Alert box. Whenever I place the script inside the php file my a link is located, it works fine, but whenever I place it in my custom JS file, it doesn't detect it, and I get the error 'Uncaught TypeError : Cannot set property "onclick" of null'.
The link between the php page and custom js page is definitely working, as I have previous working code on the page. It simply wont detect my A link it its located in an external script.
HTML
<a id="ConfirmHolidayClose" href="#">
<img src="assets/img/close-button.png" alt="Holiday-request-close-button"
class="CloseButton" />
</a>
JAVASCRIPT
document.getElementById("ConfirmHolidayClose").onclick=function(){
alert("Working");
}
UPDATE - Forgot to mention sorry, my a link is nested inside div called 'ConfirmHoliday'.
I have JS code manipulating the ConfirmHoliday div inside my Custom JS, so it cant be loading after because it is finding its parent div perfectly well at the moment.
The javascript file runs before the element is created, thus it doesn't exist. To solve this, you have couple options:
1) Surround the code with a window.onload function
window.onload = function () {
// Your code here
};
2) Put it in a separate js file and add a defer property to the script tag.
<script src="yourScript.js" defer="defer"></script>
3) Put the script tag after the anchor tag
It's trying to access the ConfirmHolidayClose element before it exists maybe? Where is your JS loaded in your page? I'm guessing in your <head>
A few solutions:
1) Move your script to bottom of page just above </body>
2) wrap your JS in dom ready function, this ensures no JS will run until the DOM tree exists. Easiest with jQuery, example below...
jQuery example
$(function() {
document.getElementById("ConfirmHolidayClose").onclick=function(){
alert("Working");
}
});
Vanilla example
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("ConfirmHolidayClose").onclick=function(){
alert("Working");
}
});
Using a method recommended by a user in a previous question I used just one document (index.php) to show different contents instead of creating one file for each one.
This is the code:
HTML
Home
More info
Contact Us
<div id="index">...index content...</div>
<div id="more_info">...more info content...</div>
JS
$(document).ready(function(){
function more_info(){
$('#index').hide();
$('#more_info').show();
}
});
PHP
<?php
if (isset($_GET['id_page'])) {
$id = $_GET['id_page'];
if ($id == 1) {
?>
<script>
more_info();
</script>
<?php
}
}
?>
That's not working. But if I change <script> more_info(); </script> for:
<script>
$(document).ready(function(){
$('#index').hide();
$('#quienes-somos').show();
});
</script>
It works. Why is this?
It looks like the problem you are having is because you are defining your more_info function inside of a function. This takes it out of the global scope which will not make that function accessible anywhere except for inside of your document ready function.
//more_info is now available globally
function more_info(){
$('#index').hide();
$('#more_info').show();
}
$(document).ready(function(){
//document ready code here
});
This should make the more_info execute when you output the JS function from PHP. Also it is good to note that since you are not executing the function on ready you will need to make sure the html is available for the JS to modify it. It is normally best practice to put all your JS just before the closing tag. This will ensure your html loads as quickly as possible and your JS will always have access to the HTML you are attempting to edit. With the JS in the head tag you need to make sure your JS is being called at the correct time using:
$(function() {
});
OR
$(document).ready(function() {
});
OR
$(window).load(function() {
});
All of these methods execute at different times during page initialization. With JS in the head tag your browser will need to download all the JS to the client before it can begin to render the HTML which will also add to time between going to the site and actually seeing the site.
The common method of starting jQuery is putting it in
$(document).ready(function() {
// put all jQuery stuff here
});
But what if I have a complicated site which uses basic jQuery in <head> and some custom functions that depend on the page type (e.g. if I have login page, fire some login ajax stuff).
So, how can I attach code to $(document).ready() or fire it later? Which JS syntax should I use?
Thanks for help!
My page structire is similar to this:
Display static header using PHP's include()
Add content inside <body></body>
Display the template footer
<?php
include_once('system/classes/class.display.php');
$d = new IFDisplay();
$d->display_header(array('subtitle' => 'Log In')); <-- Here it displays static
head tags. There is
document.ready in there.
I can't change it.
?>
<script type="text/javascript">
AND WHAT DO I NEED TO PUT HERE
</script>
<div>...</div>
<?php
$d->display_footer();
?>
If you aren't worried about race conditions, you should be able to use this:
$(function(){
//put your code here
});
As many times as you like.
If you have a block of code that you want to be able to run BOTH in a $(document).ready() function and sometime later like when an ajax call completes, then you can just define a function and call it both places like this:
// define this in the global scope or some other publicly available scope (not inside a document.ready() call).
function myOperation() {
// put your code here
}
$(document.ready(function() {
myOperation();
});
And, then sometime later (like in an ajax call in your other code), you can call that same function with this:
myOperation()
I'm using Phonegap to build a small (test only) Macrumors application, and remote hosts actually work (there is no same host browser restrictions). I am using the jQuery Load() function to load the contents of the Macrumors homepage http://www.macrumors.com/ into a bin, hidden div, then the each function to loop through all the article classes to show the title in a box with a link to the page.
The problem is, after the Macrumors HTML content is loaded, the each function doesn't work with the article class. Also, in the load function (which allows you to specify certain selectors, id's and classes included, to only load in those sections of the page) the class doesn't work; none of the classes do, in both the load function and each function. And many Id's don't work in the each function either.
Can anybody explain this to a noob like me?
Here is the code:
function onDeviceReady()
{
// do your thing!
$('#bin').load('http://www.macrumors.com/ #content');
$('.article').each(function(){
var title = $('a').html();
$('#content').append('<b>'+title+'</b>')
});
}
And the HTML stuff
<body onload="onBodyLoad()">
<div id="bin">
</div>
<div id="content">
</div>
</body>
I sincerely apologize if there's some very simple mistake here that I'm missing; I'm a major JS newbie.
.load() is asychronous. It hasn't completed yet when you're executing .each(). You need to put your .each() and any other code that wants to operate on the results of the .load() in the success handler for .load().
You would do that like this:
function onDeviceReady()
{
// do your thing!
$('#bin').load('http://www.macrumors.com/ #content', function() {
$('.article').each(function(){
var title = $('a').html();
$('#content').append('<b>'+title+'</b>')
});
});
}
I'm also guessing that your .each() function isn't working quite right. If you want to get the link out of each .article object, you would need your code to be like this so that you're only finding the <a> tag in each .article object, not all <a> tags in the whole document:
function onDeviceReady()
{
// do your thing!
$('#bin').load('http://www.macrumors.com/ #content', function() {
$('.article').each(function(){
var title = $(this).find('a').html();
$('#content').append('<b>'+title+'</b>')
});
});
}
I am new to jQuery and am stuck at some strange issue. I am using jQuery's change and click methods. They are working fine when used in my HTML file in the <script> tag.
Like:
<script>
$("select,input").change(function ()
{
// My code and some alerts
});
</script>
When I copied the same in external JavaScript code without <script> and imported that in my HTML it was not at all working.
Are there any changes which are needed to use jQuery in external JavaScript code?
PS: Some other non-jQuery functions present in same external JavaScript code are successfully called from HTML.
First off, you don't want a <script> tag in an external JavaScript file, if that's how I'm reading your post.
The trick with jQuery is that your code is set to execute immediately.
You want to wrap your script so that it loads when the document is ready, in something like:
$(document).ready(function(){
$("select,input").change(function ()
{
// My code and some alerts
})
});
And you want to make sure that your file is loaded after jQuery (otherwise the $ global will not be set).
Additions:
Here is what your HTML should look like:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="jscript/myExternalJs.js"></script>
Here is what your JavaScript code should look like (note there is no script tag inside the JavaScript file):
$(document).ready(function(){
$("select,input").change(function ()
{
// My code and some alerts
})
// Other event handlers.
});
As far as your other script... it sort of depends on what you're doing. The most important thing is to not try to hook event listeners up to objects that don't yet exist, which is why we use document.ready.
Did you make sure jquery is defined before your own jquery code?
You should also make sure the DOM is ready when dealing with jquery:
$(document).ready(function() {
$("select,input").change(function() {
// my code and some alerts
});
// more code here if needed, etc.
});