DOM Manipulation(Click Event Not Working) - javascript

I've build an express app and its working perfectly, in the final stage I want to add some alert messages to pop when some button are clicked. But my alerts are poping without even clicking, the moment page containing the button is loaded pop up shows
In my index.js file I have a form button for deleting
<form
action="/grades/<%=grade._id%>?_method=DELETE"
method="POST"
class="delete-form"
>
<input
type="submit"
class="btn btn-danger mt-3"
value="Delete Class"
id="delBtn"
>
</form>
I've given ID delBtn for the button,
and inside my main.js I have
var delBtn = document.querySelector('#delBtn');
delBtn.addEventListener('click', alert('Button Clicked'));
How can I get this to work properly..

This line is the problem. You call alert immediatelly.
delBtn.addEventListener('click', alert('Button Clicked'));
it will behave just like this
alert('Button Clicked');
delBtn.addEventListener('click', undefined);
The addEventListener function expects a string and a function but you are not passing in a function but undefined since that is what alert function returns.
So all you need is this
delBtn.addEventListener('click', function(){
alert('Button Clicked');
});

I think you missed callback function in event listener
delBtn.addEventListener('click', function(){alert('Button Clicked')});

Related

Print functionality is working on document load not on button click

I have one print button & on click of that button I want to print other pdf as per the link will provide not the same page. but for now print functionality is working on page load not on button click
function print (doc) {
var objFra = document.createElement('iframe');
objFra.style.visibility = 'hidden';
objFra.src = doc;
document.body.appendChild(objFra);
objFra.contentWindow.focus();
objFra.contentWindow.print();
}
print();
<input type="button" id="bt" onClick="print()" value="Print PDF"/>
Your print method is getting invoked on button click, but since it's visibility is set to hidden, it is not visible. You also have print method invoked on the page load.
function print (doc) {
var objFra = document.createElement('iframe');
//objFra.style.visibility = 'hidden';
objFra.src = doc;
document.body.appendChild(objFra);
objFra.contentWindow.focus();
objFra.contentWindow.print();
}
print('path');
<input type="button" id="bt" onClick="print('somePath')" value="Print PDF"/>
You may call your print function on $(document).ready(function(){}) function.

addEventListener function works at the beginning without being fired [duplicate]

This question already has answers here:
Why does click event handler fire immediately upon page load?
(4 answers)
Closed 4 years ago.
So here are my HTML codes:
document.getElementById("sub").addEventListener("click", testing());
function testing() {
document.getElementById("demo").innerHTML ="good";
}
<input type="submit" value="Place Order" id="sub"/>
</fieldset> </form>
<p id="demo"></p>
<script type="text/javascript" src="Q4.js"></script>
In which I declared a button to submit the form.
I added an event to the submit button to run the function testing().
I expected that when the user clicks on the button submit, the page will prompt "good". But, as soon as I load the page, "good" already appeared without clicking in the button.
result page
Why does this happen?
You should remove parentheses to prevent function testing() to be executed. Just put the name of the function.
You can find more details and simple example of listener here.
Here is a working snippet :
/*file javaScript Q4.js*/
document.getElementById("sub").addEventListener("click", testing);
function testing() {
document.getElementById("demo").innerHTML ="good"; }
<input type="submit" value="Place Order" id="sub"/>
</fieldset> </form>
<p id="demo"></p>
<script type="text/javascript" src="Q4.js"></script>
You can also put your function directly into your listener, like this :
document.getElementById("sub").addEventListener("click", function() {
document.getElementById("demo").innerHTML="good";
});
About the bug that "show the good word for a second only" :
Clicking the button causes the form to be submitted, which means the page reloads or the loads the URL in action. That means that all
temporary changes that JavaScript made in the current page load are
gone. Thanks Felix Kling
Change this line :
document.getElementById("sub").addEventListener("click", testing());
to
document.getElementById("sub").addEventListener("click", testing);
addEventListener function accept two parameters
Event name
Callback function
options (optional)
So you had called function inspite of passing function reference there.
Write it down to like below
document.getElementById("sub").addEventListener("click", testing);
OR
document.getElementById("sub").addEventListener("click", function testing() {
document.getElementById("demo").innerHTML ="good";
})
You don't need parenthesis.
document.getElementById("sub").addEventListener("click", testing);

Loading javascript function on button event

I would like to call a Javascript function once the button is displayed on screen. What I am looking for is similar to the 'onclick' attribute:
<input type="button" class="button-class" onclick="function(this)">
However, I would like the function to be called as soon as the button is displayed on screen i.e. it should be instantaneous (button creation=function call). I have already tried 'onload' but this does not seem to work. Is there a way to do this please?
Thank you
Put an script element invoking the function after the button element
<input type="button" class="button-class" onclick="fn(this)" value="button" id="btn">
<script>
function fn(obj){
console.log(obj)
}
fn(document.getElementById("btn"));
</script>
#Questionnaire, you can't do what you want since an action should take place for a button (click event) to execute code.
As a good practice, load your Javascript code after the page is done loading. This is to avoid blocking the rendering of HTML code since
Javascript is synchronous.
...
<script type="text/javascript">
function init() {
// Code for your button function here
}
window.onload = init();
</script>
</html>
The code above is pretty much it.
Just write the function name in onclick property instead of function(this) like the following..
<script>
function myFunc(e){
//do something
}
</script>
<input type="button" class="button-class" onclick="myFunc(this)">
#Bartman pointed out how the .ready() funtion handled it as a document.ready.
So i came up with a small solution to run the waanted funtion once the input button is created. Hotfix but cant imagine another solution
I hope this helps. If not please add a comment so i can edit the answer.
function clickFunc(e) {
alert("click event");
}
function loadFunc() {
alert("load event");
}
$("#button").click(function() {
$("div").append("<input id=\"but\" type=\"button\" class=\"button-class\" onclick=\"clickFunc(this)\">");
$("body").append("<script>loadFunc();<\/script>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="button" type="button">
<div></div>

Tampermonkey Click This Button

I have spend the last day trying to auto click this button to no avail. The source for the button is this.
<button type="button" class="btn btn-success ng-binding" ng-click="save()" ng-disabled="saveButton.disabled">Save</button>
The button only pops up after a couple of button clicks so I have been looping my scripts just in case.
My first solution (which returns a whole bunch of errors with reloading):
$(function(){
document.getElementsByClassName("save()")[0].click();
});
And my second one (which does nothing):
$(function(){
document.getElementsByClassName("btn btn-success ng-binding")[0].click();
});
I will keep trying different stuff while hopefully waiting for an answer and will update if I find something that works.
Your first solution doesn't work because save() is not a class name of your button, so getElementsByClassName() will return an empty array whose first element is of course undefined, so it doesn't have a click() function.
Your second solution works perfectly fine. I added a click listener to the button and then your solution. As you can see, the event is fired and the alert in the event listener is displayed.
document.getElementsByClassName("btn btn-success ng-binding")[0].onclick = function() {
alert('Button clicked!');
};
document.getElementsByClassName("btn btn-success ng-binding")[0].click();
<button type="button" class="btn btn-success ng-binding" ng-click="save()" ng-disabled="saveButton.disabled">Save</button>

Which gets executed first? onclick or ng-click

Now, I have a button and I have a validation process taking place in its click [onclick]. I have a web service call and other processes if the validation is successful, which I have in the ng-click. I doubt validation is not taking place.
My Page:
<script>
validate(){
// my validation code goes here...
}
</script>
<input type="button" id="btnLogin" title="Login" value="Login" onclick="validate();" ng-click="login_authentication();"/>
My Controller:
$scope.login_authentication = function() {
// My login code goes here....
}
Ideally you shouldn't be using onclick at all in angular if you can avoid it. Run validate() in your ng-click and then run login_authentication() if successful. Alternatively use angular's ng-form style validation for your inputs.
You should avoid using onclick in angularjs.
For answer of your question onClick will be called first
I tried this code which tells that that onClick will be called first.
<div ng-controller="ControllerZero">
<button ng-click="angularNgClick()" onclick="jsClick()">Click</button>
</div>
function ControllerZero($scope) {
$scope.angularNgClick = function() {
alert('Angular NG Click');
};
}
var jsClick = function() {
alert('js on Click');
};
DEMO

Categories