How to prevent default on form submit? - javascript

If I do this I can prevent default on form submit just fine:
document.getElementById('my-form').onsubmit(function(e) {
e.preventDefault();
// do something
});
But since I am organizing my code in a modular way I am handling events like this:
document.getElementById('my-form').addEventListener('onsubmit', my_func);
var my_func = function() {
// HOW DO I PREVENT DEFAULT HERE???
// do something
}
How can I prevent default now?

The same way, actually!
// your function
var my_func = function(event) {
alert("me and all my relatives are owned by China");
event.preventDefault();
};
// your form
var form = document.getElementById("panda");
// attach event listener
form.addEventListener("submit", my_func, true);
<form id="panda" method="post">
<input type="submit" value="The Panda says..."/>
</form>
Note: when using .addEventListener you should use submit not onsubmit.
Note 2: Because of the way you're defining my_func, it's important that you call addEventListener after you define the function. JavaScript uses hoisting so you need to be careful of order of things when using var to define functions.
Read more about addEventListener and the EventListener interface.

All you have to do is add a parameter to your function and use it inside.
var my_func = function(event) {
event.preventDefault();
}
The parameter inside now represents the parameter from the addEventListener.

i known this is old, but just for the sake of it.
try
document.getElementById('my-form').addEventListener('onsubmit',
function(event){event.preventDefault();my_func();});
var my_func = function() {
// HOW DO I PREVENT DEFAULT HERE???
// do something
}

Related

jQuery events: disable namespaces (or use an event with a period in the name)

I am trying to use .one() to bind to an event with the name similar to something.else.thing, I am not able to change the event name since it comes from an external library.
The problem is because of the periods, jQuery creates namespaces, else and thing for the event something instead of creating an event named something.else.thing.
Is there any way around this?
Thanks
Edit:
Some example code:
$(document).on('appfeel.cordova.admob.onAdLoaded', function() {
console.log('Does nothing');
});
document.addEventListener('appfeel.cordova.admob.onAdLoaded', function() {
console.log('Works');
});
I don't think you can disable jQuery event namespacing so if you want to use one on an event with dots in it you can just do this in pure JS:
Fiddle: http://jsfiddle.net/AtheistP3ace/8z6ewwnv/1/
HTML:
<div id="test"></div>
<button id="mybutton">Run event again</button>
JS:
var test = document.getElementById('test');
var button = document.getElementById('mybutton');
var event = new Event('something.else.blah');
function onWeirdEvent () {
test.removeEventListener('something.else.blah', onWeirdEvent);
alert('did it');
}
test.addEventListener('something.else.blah', onWeirdEvent, false);
test.dispatchEvent(event);
button.addEventListener('click', function (e) {
test.dispatchEvent(event);
}, false);
Its essentially the same thing. If you really want everything to seem jQuery-ish create a custom plugin:
Fiddle: http://jsfiddle.net/AtheistP3ace/8z6ewwnv/2/
$.fn.customOne = function (eventString, fn) {
var self = this[0];
var origFn = fn;
fn = function (event) {
self.removeEventListener(eventString, fn);
return origFn.apply(self);
};
self.addEventListener(eventString, fn, false);
};
$.fn.customTrigger = function (eventString) {
var event = new Event(eventString);
var self = this[0];
self.dispatchEvent(event);
}
$('#test').customOne('something.else.blah', function () {
alert('did it');
});
$('#test').customTrigger('something.else.blah');
$('#test').customTrigger('something.else.blah');
Here is how I decided to go about solving this issue. I went about it this way because this way allows me to continue to use jQuery and all the functionality it provides while keeping my code consistent and only requires a few lines of extra code to go about.
$(document).one('somethingElseThing', function() {
console.log('Event!');
});
document.addEventListener('something.else.thing', function() {
$(document).trigger('somethingElseThing');
});
What I am doing is using straight JavaScript to create an event listener for the event with a period in the name and then I have it trigger a custom event that doesn't a have a period so that I can continue to use jQuery. This I believe is an easy straightforward approach.

pass through current target name to function

I'd like to dynamically create event listeners for multiple buttons, and subsequently, show a particular frame label depending on the button clicked, but I'm unsure what to pass through (FYI, this is will be used for HTML5 canvas in Flash CC, but principally the same should apply to a web page for showing divs etc). I currently have this:
var butTotal = 4;
var selfHome = this;
function createListeners () {
for (var i=0; i<butTotal; i++) {
selfHome["btn" + i].addEventListener('click', openPop);
}
}
function openPop () {
alert("test");
selfHome.gotoAndPlay("pop"+event.currentTarget.name.substr(3));
}
createListeners();
It creates the listeners fine, but I don't really know where to start with passing through the current button instance name to tell it which frame label to gotoAndPlay.
Based on the code that you have, I'd simply change the .addEventListener() to call a generic function (rather than openPop, directly), and pass it the reference to the button. So, this:
selfHome["btn" + i].addEventListener('click', openPop);
. . . would become this:
selfHome["btn" + i].addEventListener('click', function() {
openPop(this);
});
At that point, you would then have to update openPop to accept a parameter for the reference to the element that triggered it . . . something like:
function openPop (currentButton) {
At that point, you could reference the clicked button, by using currentButton in the openPop logic.
I'm not sure I totally understand your question. However if you just need to pass the button instance (in you case "selfHome["btn" + i]") you could call an anonymous function in your event handler which calls openPop() with the button instance as an arugment. Would this work for you?
var butTotal = 4;
var selfHome = this;
function createListeners () {
for (var i=0; i<butTotal; i++) {
var currentBtn = selfHome["btn" + i];
currentBtn.addEventListener('click', function(){openPop(currentBtn);} );
}
}
function openPop (btn) {
alert("test");
selfHome.gotoAndPlay(/*use button instance 'btn' to find frame*/);
}
createListeners();
When the event is triggered the this keyword inside the handler function is set to the element is firing the event EventTarget.addEventListener on MDN. If the button have the data needed to be retrieved just get it from the this keyword:
function openPop (btn) {
alert(this.name);
/* ... */
}
It looks like you expect it to contain the function gotoAndPlay() as well as the btn elements (which contain both an ID (of btn[number]) and a name with something special at substr(3) (I assume the same as the id). If those things were all true, it should work in chrome... in other browsers you'll need to add event to the openPop() method signature.
function openPop (event) {
alert("test");
selfHome.gotoAndPlay("pop"+event.currentTarget.name.substr(3));
}
I believe this is what you are looking for and adding that one word should fix your problem (assuming some things about your dom and what selfHome contains):
JSFiddle
You could also leave out the event from openPop() and replace event.currentTarget with this:
function openPop () {
alert("test");
selfHome.gotoAndPlay("pop"+this.name.substr(3));
}
JSFiddle

Javascript - Function to use onclick?

I want to create a function and then use with onclick method, for example:
one = document.getElementById("oneID");
then instead of writing function for each onclick():
one.onclick = function(x) {
tempStack.push(parseFloat(one.value));
viewTemp.value += one.value;
}
I want to use a single function:
one.click = input(one);
but I'm not sure how to do it in the correct way for example the below I tried, doesn't work:
var input = function(x) {
tempStack.push(parseFloat(x.value));
viewTemp.value += x.value;
}
Lastly, no external JavaScript libraries to aid this question, vanilla JavaScript.
You'll need to pass a function as a reference, not call it:
one.onclick = input;
In this case you won't be able to pass an argument, but you can use this as a reference for the DOM element on which event is fired:
function input() {
tempStack.push(parseFloat(this.value));
viewTemp.value += this.value;
}
Here's a method with using JavaScript's .addEventListener(), as a previous answer mentioned, using this to pass through the DOM Node Element to use within the inputFunction.
<input type="text" value="64.23" id="bt" />
<script>
function inputFunction( x ) {
console.log( x.value ); //Console Logs 64.23
}
var bt = document.getElementById("bt");
bt.addEventListener( 'click', function(){ inputFunction( this )}, false );
</script>
Fiddle: http://jsfiddle.net/Lhq6t/
Think about functions as a normal objects, so the way is:
function input (event) {
// Process the event...
// event is my event object
// this is the object which trigger the event
// event.target is my button
}
on.onclick = input;
You must assign the input function as a normal variable.
The function input will receive an event object as parameter. Also you can refer to the button clicked with this.
Maybe the mozilla developer network or the real w3c site would explain it better.
Your requirement can be achieved by following:
Add this method in your script tag:
function input(x) {
/*tempStack.push(parseFloat(x.value));
viewTemp.value += x.value;*/
alert(x.id);
}
And then call this method onClick event of your buttons / anchors like:
<input type="button" id="oneID" value="oneID" onClick="input(this);"/>
<input type="button" id="twoID" value="twoID" onClick="input(this);"/>
threeID
See working example: http://jsfiddle.net/Avd5U/1/
ok, so just create a function with a parameter in it like:
function setValue(input){
tempStack.push(parseFloat(input.value));
viewTemp.value += input.value;
}
and then call the function on the click of that element like:
var one = document.getElementById("oneID");
one.click = setValue(one);
Good luck!

Javascript Iteration issue

I am trying to iterate over the following Code and for some reason each time i iterate over it, it fires off the event handler, does any one know why it would be automatically firing off the handler?
nmbr = 1;
x1 = document.getElementsByClassName('fp')[0] ;
slowSkrol = document.createElement('button');
slowSkrol.className = 'mods';
slowSkrol.value= nmbr;
x1.appendChild(slowSkrol);
slowSkrol.addEventListener('click', whenclicked(nmbr),false);
function whenclicked(vv){
alert(vv);
}
You are calling the function, and binding it's return value to the event, rather than binding the function itself to the event. Replace whenclicked(nmbr) with:
function(){ whenclicked(nmbr); }
In modern browsers you could also use bind:
whenclicked.bind(null, nmbr);
change:
slowSkrol.addEventListener('click', whenclicked(nmbr),false);
to
slowSkrol.addEventListener('click', function() {
whenclicked(nmbr);
},false);
I shouldn't be adding another answer really. but the correct way to do this so that you get all arguments and the this would be like so.
slowSkrol.addEventListener('click', function( event ) {
whenclicked.apply(this, [event, nmbr]);
}, false);
Then you can use it like so.
function whenclicked( event, nmbr ){
alert(this, event, nmbr);
// this = slowSkrol
}

Calling JS functions from Href

I'm curious whats the best way to call a JS function with a href link in HTML. I don't use a library and i see alot of mention about jquery using event handlers ...
But if im not using a library can it still be done or will i have to use an on click type call ?
You can use event handlers with plain javascript. No framework is required. Here's a cross browser function I use:
// add event cross browser
function addEvent(elem, event, fn) {
if (elem.addEventListener) {
elem.addEventListener(event, fn, false);
} else {
elem.attachEvent("on" + event, function() {
// set the this pointer same as addEventListener when fn is called
return(fn.call(elem, window.event));
});
}
}
And, an example of using it would be like this:
HTML:
<a id="myLink" href="#">Click ME</a>
Javascript:
var link = document.getElementById("myLink").
addEvent(link, "click", function(e) {
// process the click on the link here
});
If you don't want the default click of a link to happen, then you need to prevent the default behavior from the event handler like this:
var link = document.getElementById("myLink").
addEvent(link, "click", function(e) {
// process the click on the link here
// prevent default action of the click
if (e.preventDefault) {
e.preventDefault(); // normal browsers
} else {
e.returnValue = false; // older versions of IE (yuck)
}
});
try this
function test() { alert (''); }
<a href="#" onclick="test();" />
Basically there are two ways:
...
and
...
(in this case someFunction must return false)
I prefer the latter.

Categories