javascript onclick null in custom js file - javascript

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");
}
});

Related

Jquery on Wordpress Frontend not woorking

Maybe I am so noob with jQuery but cant reach my objective. I need to add the attribute target="_blank to all the links inside certain divs. But anything I do works.
I have checked for jquery loaded with:
if(wp_script_is('jquery')==false) {
wp_enqueue_script("jquery");
}
Using the the following code nothing happens:
jQuery("#adagal").html("<p>asdf*</p>");
The #adagal element remains with previous content. I have checked in the source if my javascript file was correctly added, and it is.
<script type='text/javascript' src='http://localhost/wordpress/wp-content/plugins/AdManagerAdagal/js/ads/show_ad.js?ver=4.3.1'></script>
So, what is the problem¿?
Use that:
jQuery(document).ready(function($)
{
$(".your_class a").attr("target", "_blank");
});
Don't forget $ in ready(function to use jquery in your js

Javascript adding <script> tag after page loads

Got a little problem here. Basically, I'm trying to add a script tag after the page loads.
This is what I am doing:
index.php:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function getad()
{
$.post('assets/getad.php', "ad", function(response) {
response = response.replace('document.write','document.getElementById("ad").innerHTML = ');
eval(response);
console.log(response);
});
}
getad();
</script>
<div id="ad"></div>
</body>
</html>
getad.php:
<?php
echo file_get_contents("http://ads1.qadabra.com/t?id=a823aca3-9e3c-4ddd-a0cc-14b497cad85b&size=300x250");
?>
You can find a demo here: http://dev.cj.gy/game/
As you can see, the #ad div DOES get filled with the correct script tag, but it doesnt actually run, If I edit the page to include the script tag right at page load, it does run.
Yes, <script> tags cause execution when parsed as part of the main document; they don't execute from being written to innerHTML.
You can create an executing script element outside of that initial parse using the DOM method of calling createElement('script'), setting its src/content and adding it to the document. This is what jQuery's getScript does.
However it wouldn't do you much good because the next script, that ads1.qadabra.com is document.writeing to the page, also itself calls document.write.
You could work your way around both of these calls at the client side (ie without getad.php), by assigning your own custom function to document.write that, instead of writing to the loading page, attempts to extract the source of the script tag passed to it, and load that in a DOM-created script element.
But in general these are scripts designed to work synchronously at document load time; anything you do to try to force them to run in a way they weren't intended to is likely to be fragile and stop working when the ad network change anything.
If you want to load a third-party ad without pausing the loading of the parent document, I suggest putting it in an iframe.

Can't call javascript from ajax div

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);
}
});

How to execute Javascript from external HTML

If I have a button that executes the code
$('#main').load('welcome.html');
and in welcome.html I have a button that executes the code
$('#main').load('otherpage.html');
the Javascript isn't executed, regardless of whether that function is on the parent file's HTML code or the child's.
How can I get a Javascript function to work from externally loaded HTML files?
EDIT
Here's a bit more of a sample...
Homepage:
<body>
<div id="main"></div>
</body>
<script>
document.onLoad(){
$('#main').load('welcome.html');
}
function show(file){
$('#main').load(file+'.html');
}
</script>
welcome.html page:
Test
...however when the Test button is clicked, test.html is not loaded into the Main div.
EDIT 2
Here is what the current state is and what the issue is - exactly.
I've uploaded the bones of the code to PasteBin.
When the 'grid' button is clicked, the content changes and the footer changes.
However, the footer, which has URLs based on Javascript, comes up with the error:
Uncaught SyntaxError: Unexpected token ILLEGAL
...when trying to access the 1i.html page.
There's a difference between test the variable and 'test' the string:
Test
Probably should be:
Test
It is important to understand that when loading script into page via AJAX that the main page has already gone through document.ready . Thus, any code you load will fire immediately.
If the code you load precedes the html it references, it will not find that html when it fires.
Placing the code after the html in remote page will resolve this issue
Check jQuery.live() and jQuery.on().
Maybe your eventhandler is wrong. When you import new markup via load() or ajax(), you have to initialize the handlers from new document. The easiest way is using jQuery.on or jQuery.live() instead of jQuery.click().
$('MYBUTTON').live('click', function(){
$('#main').load('your_url.html')
})
or use the callbackfunction to (re-)initialize the buttons event.
A better solution is this: Just add the target_url to buttons rel attribute...
<button rel="YOUR_URL.html">Open Page</button>
$('button[rel]').live('click', function(){
$('#main').load($(this).attr('rel'));
})

Changing content of a div with clicking on a div [jQuery]

I'm trying to change the content of the portfolio section of my website. I have a div called .portfolio_box, which contains a small preview of the project (each project div also has a different id). When you click on this div (.portfolio_box) I want the content of the content div (#main_content) to go away and be replaced with the corresponding content.
I found the following tutorial and adjusted the script to my needs:
<script type="text/javascript">
$(document).ready(function()
{
$("#thomasschoof_old").click(function()
{
/*hide( 'fast', function()
{
$('#main_content').load(thomasschoof_old.html,'',showNewContent);
} );
var toLoad = $(this).attr('href')+' #main_content'; */
$('#main_content').hide('fast',loadContent);
$('#page').append('<span id="load">LOADING...</span>');
$('#load').fadeIn('normal');
});
function loadContent()
{
$('#main_content').load('thomasschoof_old.html #project','',showNewContent)
}
function showNewContent()
{
$('#main_content').show('normal',hideLoader);
}
function hideLoader()
{
$('#load').fadeOut('normal');
}
return false;
});
</script>
But when I click on the div #thomasschoof_old nothing happens. I don't know a lot about jQuery or Javascript (just getting into it) and I really can't get it figured out.
You can view the web page here: http://jowannes.com/thomasschoof/portfolio.html
I hope somebody can help me, Thanks in advance!
Thomas
Your problem is, that you wrote your JS code inside scripts tags that are used to load an external script file (jQuery). You script just wont ge executed that way.
src: This attribute specifies the URI of an external script; this can
be used as an alternative to embedding a script directly within a
document. script elements with an src attribute specified should not
have a script embedded within its tags.
From: https://developer.mozilla.org/en-US/docs/HTML/Element/Script
Set up a separate script tag for you code or include it from a second external script-file and see what happens.

Categories