Javascript function not being run from click - what am I doing wrong? - javascript

I am currently making some accessibility options which make the font size increase or decrease on a page. Following EndangeredMassa's for calling JS from a link it appears not to work!
My current code (which is dummy code with the right IDs which will be used in my actual site), does not even run a Javascript alert, and since I'm not one for Javascript, if anyone could let me know what I'm doing wrong.
HTML
<p id="html">Nice to meet you!</p>
<a id="incFontS" href="#">Increase Text</a>
JavaScript
var incFont = document.getElementById("incFontS");
incFont.onClick = function () {
window.alert("it ran!");
}
As you can see from my jsfiddle, the code does not work at all, and I haven't even gotten to the part where I start changin the font sizes (geh!).
Any help is greatly appreciated!

Case matters in JavaScript. The correct property name is onclick (with a lowercase 'c'). Try this:
var incFont = document.getElementById("incFontS");
incFont.onclick = function () {
window.alert("it ran!");
}
Demonstration
Also, be sure to read addEventListener vs onclick for a discussion about different techniques for binding event listeners.

DEMO
var incFont = document.querySelector("#incFontS");
incFont.addEventListener('click', function () {
window.alert("it ran!");
return false;
});

The function name is onclick not onClick
i.e.
var incFont = document.getElementById("incFontS");
incFont.onclick = function () {
window.alert("it ran!");
}
works for me.

Try this way to do increase your font size
HTML CODE
<p id="html">Nice to meet you!</p>
<a id="incFontS" href="#" onclick="myFunction()">Increase Text</a>
Java Script Code
<script>
function myFunction() {
document.getElementById("html").style.fontSize="xx-large";
}
</script>

Related

JavaScript and WordPress: button click not found by addEventListener

To prevent answers like: 'is the JavaScript file loaded?' -> Yes, it is loaded, at the footer part of the page! I have checked that with a simple message to the console, which is displayed!
But:
I've got a page with a button:
<button id="portfolio-posts-btn">Load portfolio related blog posts</button>
And a file main.js:
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
The text the button was clicked! should be displayed in the console, but it stays empty!
Apparently, the button click is not recognized, and thus, the var portfolioPostsBtn is false, or NULL... -> the method addEventListener() is not fired ?
I don't see the cause for this; I checked the spelling, should I use single or double quotes? Please help?
Thank you!
I've had this happen to me before, since theres two ways to do this I just used the other.
The first is onclick="function()", this is used as an attribute inside the element. Ex:
function clicked(){
alert("button clicked");
}
<button onclick="clicked();">Press me</button>
exaplaination: When you add this attribute to this element and I do believe some others when the button is clicked the specified code inside the quotes of the attibute will run. It doesn't have to be a number, e.g. onclick="alert(12+4/2);". But this is more of HTML than JavaScript using this version
The other way is using what you've got which (to me) is a lot more difficult then it needs to be. Heres my example
var b = document.getElementById("btn");
b.addEventListener("click", blogged);
function blogged(){
alert("this post has been blogged");
}
<button id="btn">Blog it</button>
This side of things has more to do with JavaScript and Event listeners. But the problem with you're code is that you're putting the event listener after you call the if statement. Here's my solution
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
portfolioPostsBtn.addEventListener("click", function(){
check();
});
function check(){
if(portfolioPostsBtn){
console.log("posted");
}
}
<button id="portfolio-posts-btn">press this to post<button>
Presumably you have made a decision not to use jQuery. You'll need to wrap your code in an event listener so that the code is executed when the DOM is ready.
document.addEventListener("DOMContentLoaded", function(event) {
var portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
});
The answer is found in the uploading of the file page-portfolio.php!
I found out that the id="portfolio-posts-btn", added later, was not updated - could be my mistake, or the SFTP upload extension in Brackets - I did not see an error message!
Anyway, the issue is solved!
One more question: "are there methods to check if an id exists?". That could make live easier!
All contributors, thank you for your answers!

addEventListener Module Pattern

I don't know why but when I click on "button" nothing happens...
No message in console, no error. How to fix it ?
JS
var bird = (function(){
let button = document.querySelector('#addBird');
button.addEventListener('click', addBird);
function addBird()
{
console.log('addBird');
};
return {
addBird: addBird
};
})();
HTML
<button id="addBird">Add Bird</button>
Just tried this example in CodePen:
http://codepen.io/JasonGraham/pen/pbowXz
var bird = (function(){
let button = document.querySelector('#addBird');
button.addEventListener('click', addBird);
function addBird()
{
console.log('addBird');
};
return {
addBird: addBird
};
})();
As far as I can see, your code appears to be working as expected. In Chrome, clicking on the button causes the "addBird" message to be logged to the console each time.
Are you expecting something different?
This happens because the JavaScript loads before the DOM (basically, the HTML markup) is ready. Therefor, the button variable equals NULL.
Two ways to solve this:
Move your JavaScript at the end of the page, just before the </body> tag.
Wrap your JavaScript code with jQuery's document ready function:
$(function() {
// code here
});
Ok if I insert and outside the #birdMod It works... So it was not the .render() function. Thank you for your help. :)

addEventListener to div element

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.

Program not working on Google Chrome

I am programming a sudoku puzzle (http://www.jsfiddle.net/sZ7Aq/4/). It works okay on IE, but when I try it on Google Chrome, the button doesn't do anything when I click on it. Is there a way to fix it so it works on all browsers?
Please note: I haven't finished it so there isn't a puzzle generating function. You must enter all numbers yourself.
Here is my main() function (if you did not click on the link yet):
function main() {
getcellVal();
if (validate() == false) {
alert("Something's not right!");
return false;
}
alert("Good job!");
return true;
}
My button:
<button onclick="javascript: main()">Check my answer</button>
Use .addEventListener('click', main); For instance:
var check = document.getElementById('check');
check.addEventListener('click', main);
and of course add id="main" and remove the onclick from your button.
Updated fiddle
Then open your console and fix the other bugs...
From your jsfiddle, the error is in your getcellValue() function. This code is incorrect:
colVal = [[x0y0.value, x0y1.value, x0y2.value, x0y3.value, x0y4.value, x0y5.value, x0y6.value, x0y7.value, x0y8.value],
I would suggest you change your input elements to have an id attribute that matches the name. Like this:
<input type="text" name="x0y0" id="x0y0">
Then change your getcellVal() function to use the getElementById function.
colVal = [[document.getElementById("x0y0").value, ...],
It will be much more verbose, but it will work in more browsers.
Few things need to be corrected:
Instead of defining an event such as javascript: main() inline, use unobtrusive solution to register the necessary event handlers programmatically.
Eg:
<button id="buttonid">Check my answer</button>
window.onload = function() {
document.getElementById('buttonid').onclick = main;
};
You cannot access the DOM elements just by specifying their names. In your case x0y0.value will not return anything. Instead use id or class name to access the set of elements.
Eg:
<input type="text" name="x0y0" id="x0y0">
In javascript,
document.getElementById("x0y0").value

passing javascript variable value to swf in fdt

I am very new in FDT, I want to pass javascript variable value to FDT code.
I have no idea how to do it.
HTML Code:
<a id="player" href="javascript:void(0)" data-id="02">ABCD</a>
Javascript Code:
$('.list a').click(function(){
var id = $(this).data("id");
}
In FDT, with id 02 there is SWF file link.
Or is there any another way to do it? Please help me.
Thanks in adcance.
you need to use ExternalInterface in swf, to catch function calls from javascript
import flash.external.ExternalInterface;
if (ExternalInterface.available){
ExternalInterface.addCallback("changeText", changeTheText);
}
function changeTheText(t:String):void {
txtText.text = t;
}
JavaScript code
var flashObj = document.getElementById('flashObject');
Click me!
Example here:
http://www.hardcode.nl/archives_155/article_334-call-javascript-function-from-as3-and-viceversa.htm
Search google for "javascript/as3 bridge"
In addition to what #bFunc mentioned, I might advise doing your onclick event outside of the anchor tag, if possible. I find it best to target your elements that receive action via JS rather than embedded in the HTML code. This way, you can wrap the flashObj.changeText call in a try/catch to avoid JS errors (which may happen), and handle the error appropriately (i.e. if your SWF isn't available or loaded, like when a user doesn't have Flash Player installed).
For example:
HTML Code:
<a id="flash_bridge_link" href="#" onclick="javascript:void(0)">Click Me</a>
Javascript:
var flashLink = document.getElementById("flash_bridge_link");
var flashObj = document.getElementById("flashObject");
flashLink.onclick = function () {
try {
flashObj.changeText("it works!");
} catch (error) {
// Handle error as needed.
}
}
Hope it helps!

Categories