I'm creating a website where I'll be displaying my work. Then I noticed that I needed a Cookie Notice. Because I want to make it 100% by myself (without generators, etc.) I started creating it. The Cookies themselves are working fine, but main.js is not registering the button's onClick.
Here's the code:
var acceptButton = document.getElementById("cookieAccept");
acceptButton.onclick = function() {
alert("HELLO");
}
My button's code:
<button id="cookieAccept" class="cookieButton">Accept</button>
I've been Googling a lot, searching through StackOverflow, etc. There are no answers that worked for me (yet). Here are the solutions I tried:
jQuery
object.onclick = function() {}
object.addEventListener("click", false);
Put the object.addEventListener("click", false) inside of window.onload
Any hints/help?
- XaafCode
EDIT
Console error:
Uncaught TypeError: Cannot set property 'onclick' of null
The possible reason in this case would only be is.
This will work
<button id="cookieAccept" class="cookieButton">Accept</button>
<script>
var acceptButton = document.getElementById("cookieAccept");
acceptButton.onclick = function() {
alert("HELLO");
}
</script>
Make sure you don't have Js before html is written. First html then Js. Also make sure you don't have two id of same name . This may some time create problem.
This will not work
<script>
var acceptButton = document.getElementById("cookieAccept");
acceptButton.onclick = function() {
alert("HELLO");
}
</script>
<button id="cookieAccept" class="cookieButton">Accept</button>
Be sure to wrap your js code in a function that you'll register to be executed once the browser sets up all the html:
window.onload = function() {
var acceptButton = document.getElementById("cookieAccept");
acceptButton.onclick = function() {
alert("HELLO");
}
}
Cfr.: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
Remember to put HTML code before Javascript syntax under tag.
Related
I want to create an onclick function for button that is in div with id Restyled.
I tried this:
<script>
var RestyledDiv = document.querySelector("#Restyled");
var RestyledButton = x.querySelector("button");
RestyledButton.onclick = function() {
alert("button was clicked");
};
</script>
But I get this error: Uncaught SyntaxError: Invalid or unexpected token
You're looking for adding an event listener to the button and you can use the querySelector to go deeper than just a single selector level.
You also had two hidden whitespace characters in your code that resulted in the syntax error you were seeing.
Note the <0x200b> characters that are shown in my editor that is configured to show whitespace characters.
var RestyledButton = document.querySelector("#Restyled button");
RestyledButton.addEventListener('click', function() {
alert("button was clicked");
});
<div id="Restyled">
<button>Click me!</button>
</div>
i tried running your code and basically there are 2 things that i would like to point out:
var RestyledDiv = document.querySelector("#Restyled");
it is not needed here, you are not using the given div.
You can directly select the button by the provided id. You can delete the dive query line whatsoever.
it seems like there was something weird in your last line of code:
};
For some reason, it was not working for me, but as soon as i literally retyped the same code - it worked.
Here's how it works for me:
<script>
var RestyledButton = document.querySelector('#restyledButton');
RestyledButton.onclick = function () {
alert('button was clicked');
};
</script>
I was toying around with trying to get events-on-button-click to work where the JavaScript code triggers some event once a specific button is clicked.
There are no issues when I attempt to do on-click triggers in my project(s), but I just can't seem to get it to work using JSFiddle.
I first followed the tips here: JavaScript not running on jsfiddle.net
Specifically, the part where meder omuraliev writes, "So instead of
<p onclick="lol()" id="foo">
you'd do
var e = document.getElementById('foo');
e.onclick = lol;
in the JS only."
I attempted to follow this instruction which can be seen in the simple example I made here (that doesn't work): https://jsfiddle.net/b7yj3cph/3/
var e = document.getElementById('test');
e.onclick = example;
var example = function( {
alert("hello");
});
<button id='test' type="button" onclick="example()">
<div>
Hello
</div>
I tried other sources and methods but couldn't get any to work. I attempted an example from W3Schools (https://jsfiddle.net/b7yj3cph/) and tried some JSFiddles from searching "jsfiddle button onclick" (https://jsfiddle.net/Dogbyte/62cd0LLq/) which some didn't work.
But some did; like this one (http://jsfiddle.net/lesson8/h4JXs/1/) seems to work fine.
What is uniquely going on that makes the click trigger work for some JSFiddles and not for others? I suspect it has to do with the $(document).ready() part but I've been reading various ways to get this to work and I can't find anything that makes sense to me.
Going back to the Stack Overflow thread that I shared earlier, the top-voted response there had 3 suggestions:
"( easiest, quickest, not ideal ) - change function blah(){} to window.blah = function(){}; making the functions global."
Well, in the JSFiddle posted here that works as expected, there is no use of window. Attempts that I made to use window proved to be fruitless.
"( ideal way ) - use unobtrusive Javascript to attach behaviour to DOM elements from within the JS solely, meaning separate HTML from
JS."
This is a great point and makes sense but still didn't solve my particular
issue.
"Make the jsfiddle not wrap the stuff onload. Change onLoad to no wrap ( body or head )."
My particular example isn't wrapped in onLoad(at least, I don't think that it is). Anyways, thanks!
You have two issues in your fiddle:
Firstly your example function is declared incorrectly:
var e = document.getElementById('test');
e.onclick = example;
var example = function( { // parenthasis should be closed before opening braces
alert("hello");
});
Should be:
var e = document.getElementById('test');
e.onclick = example;
var example = function() {
alert("hello");
}
Secondly, you are declaring the var example below the onclick assignment which is being interpreted as:
e.onclick = undefined
Just move the var example above the e.onclick and fix the syntax issue and it will work:
var e = document.getElementById('test');
var example = function() {
alert("hello");
}
e.onclick = example;
This is the way if you don't want to wait for the DOM to be loaded.
document.getElementById('btnSave').addEventListener('click',() => {
alert('clicked the damn button!');
});
The reason attaching something to .onclick doesn't work is because, for that, you do have to wait for the DOM to load; order of operations is really important in this case.
Why won't this work in Confluence:
AJS.$("body").attr("onload", AJS.$("body").attr("onload") + " myFunction()");
I want to append my own function to the onload attribute of the body element but when I add this code to the Main Layout, Confluence just ignores it. When I try this code using the Chrome debugger, it works just fine.
Edit: I guess I should be a little more clear: The above code seems to work when the Confluence page is loaded the first time. But when the page enters into edit mode, the custom script isn't executed.
As a general rule, wait until the whole page has loaded. In some cases, in particular when plugins are manipulating the DOM, you may have to put in a delay of a second or two before your script runs.
Using JQuery:
{html}
<script type="text/javascript">
AJS.$(document).ready(function() {
AJS.$("#comments-section").hide();
});
</script>
{html}
Using JavaScript:
{html}
<script type="text/javascript">
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
var ele = document.getElementById("comments-section");
ele.style.display = "none";;
})
</script>
{html}
Well, it may depend on many things. For example whether myFunction is already available at the moment when the onload handler wants to execute it.
But why don't you use a more standard way of achieving this:
AJS.$(document).ready(myFunction);
or if you really want to react on the load event
AJS.$(document).load(myFunction);
Base on a discussion with an Atlassian developer, "The proper way to execute a function when the page is loaded is: AJS.$(function($){ ... your code ... });"
This does work for the initial page load but when the page goes into edit mode, this doesn't get executed. Several console.log outputs confirm this.
I'm trying to simulate a click in a tabbed div when the page loads.
To do this I use:
$(document).ready(function() {
$("#tab_inbox").click();
});
However, this doesn't seem to work, but when I enter this in the dev console on Google chrome, it does work..
$("#tab_inbox").click();
To show the tabs, I use this code:
$("#tab_inbox").click(function() {
$("#othertab").hide();
$("#tab_inbox").show();
});
Anybody knows what's wrong?
Try this:
$(document).ready(function() {
setTimeout(function () {
$("#tab_inbox").trigger('click'); //do work here
}, 2500);
});
I read in your comment that you're using show/hide techniques and I assume you need the click for an initial display option? If so, hide (or show) your element(s) specifically in the code rather than saying click to hide/show. So
$(document).ready(function() {
$("#tab_inbox").hide();
}
Or try core JavaScript and use
window.onload = function() {
// code here
}
window.onload waits until everything is loaded on your page, while jQuery's .ready() may fire before images and other media are loaded.
you can try making your own function with pure JS:
document.getElementById('triggerElement').addEventListener('click', funtction(e) {
document.getElementById('hideElement').style.display = 'none';
document.getElementById('showElement').style.display = 'block';
}, false);
I want to produce buttons through Javascript that can also do the form function. Here is how i am doing but my form function does not work when i click. Please help me out on this.
External Javascript
var onef
onef="Apple"
var twof
twof="Orange"
Now this is what i am doing in HTML page
<script>
document.write("<button>")
document.write(onef)
onClick=("this.form.T4.value++;")
</script>
<script>
document.write("<button>")
document.write(twof)
onClick=("this.form.T5.value++;")
</script>
The script works right but onClick function not working.
ouldn't you have to do this:
<script>
document.write("<button ")
document.write('onClick="this.form.T4.value++;">')
document.write(onef)
document.write("</button>")
</script>
What you are doing in your original code is building the string "<button>apple" and creating a variable called onClick with a value of "this.form.T4.value++;". What I believe you need to do is build a string with the whole button tag in it, which is what the code above is doing.
I have never seen code like this before for creating a button with JavaScript. I would go with something more like this;
var onef ="Apple";
var twof ="Orange";
function createButton(context, func, text){
var button = document.createElement("input");
button.type = "button";
button.value = text;
button.onclick = func;
context.appendChild(button);
}
createButton(document.body, function(){ this.form.T4.value++; }, onef);
createButton(document.body, function(){ this.form.T5.value++; }, twof);
An example can be seen here http://jsfiddle.net/4yV4V/
This gives you some reusable code for creating the button and passing in what ever you want the onclick even to be. Also you could customise this code for other situations.