href="javascript:Function() how does it work - javascript

Content
like this ,how does Function work?can i intercept it and if i dont use mouse how can trigger it?

It will be triggered when ever the link is "triggered", i.e. on click or when tabbing to it and pressing ENTER. You can "intercept" it by replacing Function with a custom function:
var oldFunc = window.YourFunction;
window.YourFunction = function() {
// do something
oldFunc(); // call the old function if necessary
// do more if necessary
}
By the way: You shouldn't do this at all. Use onclick="..." or even better, register an event via JavaScript. Both cases will also trigger when the link is not actually mouse-clicked but triggered by pressing ENTER.
To use onclick, the link should look like this:
...
To register the event in a modern browser (IE before v9 is not a modern browser in case it matters to you):
...
<script>
document.getElementById('whatever').addEventListener('click', YourFunction, false);
</script>
To keep it short and cross-browser compatible I'd highly suggest you to use jQuery:
...
<script>
$('#whatever').on('click', YourFunction);
</script>

You can use this if you want to use href
Content​
<script lang="javascript" type="text/javascript">
function smfunction(){
alert("Running");
}
</script>

Related

Make onclick work on iphone

I have been using "onclick" in my javascript, but now I want it to work on Iphone as well. Is there a simple way to make all "onclick" to work like ontouchstart for devices that support ontouchstart?
Or do I need to write all script twice (one that uses onclick and one that uses ontouchstart)? :S
Note: I dont want to use jquery or any other library.
<!DOCTYPE html>
<title>li:hover dropdown menu on mobile devices</title>
<script>
window.onload = function () {
if ('ontouchstart' in window) {
// all "onclick" should work like "ontouchstart" instead
}
document.getElementById('hbs').onclick = function () {
alert('element was clicked');
}
}
</script>
<a id=id1 href=#>button</a>
This post got more attention, so I'm going to add another commonly used, more up to date, trick:
// First we check if you support touch, otherwise it's click:
let touchEvent = 'ontouchstart' in window ? 'touchstart' : 'click';
// Then we bind via thát event. This way we only bind one event, instead of the two as below
document.getElementById('hbs').addEventListener(touchEvent, someFunction);
// or if you use jQuery:
$('#hbs').on(touchEvent, someFunction);
The let touchEvent should be declared out of function (also not in a document.ready) at the top of your javascript. This way you can use this in all your javascript. This also allows easy (jQuery) usage.
Old answer:
This fixes the need for copying your code (well at least to a minimum). Not sure if you can combine them
function someFunction() {
alert('element was clicked');
}
document.getElementById('hbs').onclick = someFunction;
document.getElementById('hbs').ontouchstart= someFunction;
document.getElementById('hbs')
.addEventListener('click', someFunction)
.addEventListener('touchstart', someFunction);
The reason javascript is not working on the iPhone in Safari is because iPhones have the option to turn off Javascript.
Go to "Settings"
Then scroll down to "Safari"
Then scroll all the way to the bottom "Advanced"
Then turn on Javascript!
Also, you can check if Javascript is enabled with this code:
<script type="text/javascript">
document.write("Javascript is working.")
</script>
<noscript>JavaScript is DISABLED!!!!!!</noscript>

event.preventDefault() in a href="#" doesn't prevent jumping to top of page in IE and Firefox

HTML:
<a href="#" class="button" onclick="sendDetails(\'Edu\')">
JS:
function sendDetails(type) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
names = $("#names" + type).val();
Input = encodeURIComponent($("#Input" + type).val());
....
The link jumps to top of page. I tried to use event.preventDefault() to stop jumping to top of page. However, it works only in Chrome and not in IE and Firefox. How can I solve it?
instead of "#" you can use javascript:; so there is no jumping, make sure to return false to disable the link-behavior
link
You can't only use the window.event to control an event. Try standardizing it like:
function sendDetails(e, type) {
var evt = window.event || e;
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
// ...
}
And your HTML would have to be:
ASDF
One other non-jQuery solution is to just modify your HTML to be:
ASDF
in which case you wouldn't have to use anything dealing with event in your sendDetails function. The return false; will prevent the default behavior automatically. But note - if any exceptions occur in your sendDetails function, the return false; won't execute and will allow the default behavior. That's why I like using preventDefault - you can call it immediately in the function to immediately stop the behavior, then do what you need.
At the same time, if you're using jQuery, try binding the click event like this:
$(document).ready(function () {
$(".button").on("click", function (e) {
e.preventDefault();
// Your sendDetails code (without the "event" stuff)
// OR call sendDetails (and remove the "event" stuff in the sendDetails function)
});
});
in which case your HTML would be:
ASDF
Although it would be a lot easier to target the specific elements that this applies to, instead of using the .button selector I provided. I'm sure the "button" class applies to more than just these targeted <a>, but maybe I'm wrong :)
Using jQuery is nice in this situation because it already standardizes the event object in a way that you can just use that e variable I included in the click callback. I'm sure it does a little more than just window.event || e, so I'd prefer/suggest using jQuery for handling events.
You are already using jQuery, just do it the jQuery way. jQuery wraps the event object and provides a normalized event object so you can just use the standard preventDefault, you don't need to fork depending on what the browser supports.
<button class="senddetail" data-type="edu">Education</button>
<button class="senddetail" data-type="com">Commercial</button>
<!-- why not just use a button instead of styling a link to look
like a button? If it does need to be a link for some reason
just change this back to an anchor tag, but keep the data
attributes and change the class to "button senddetail" -->
<script>
function sendDetails(type) {
// Assuming names and input are not globals you need to declare
// them or they will become implicit globals which can cause
// all sorts of strange errors if other code uses them too
var names, input;
names = $("#names" + type).val();
// you should only use capitalized variables for
// Constructor functions, it's a convention in JS
input = encodeURIComponent($("#Input" + type).val());
//....
}
// just calling $ with a function inside of the invocation
// is the same as using $(document).ready
$(function () {
// instead of using onClick, use jQuery to attach the
// click event in a less intrusive way
$('.senddetail').on('click', function (event) {
// no matter what browser this runs in jQuery will
// provide us a standard .preventDefault to use
event.preventDefault();
// jQuery sets 'this' to the DOM element that the event fired on,
// wrapping it in another jQuery object will allow us to use the
// .data method to grab the HMLM5 data attribute
var type = $(this).data('type');
sendDetails(type);
});
});
</script>

Including both href and onclick to HTML <a> tag

If I have this element:
Item
How can I make both href and onClick work, preferably with onClick running first?
You already have what you need, with a minor syntax change:
Item
<script type="text/javascript">
function theFunction () {
// return true or false, depending on whether you want to allow the `href` property to follow through or not
}
</script>
The default behavior of the <a> tag's onclick and href properties is to execute the onclick, then follow the href as long as the onclick doesn't return false, canceling the event (or the event hasn't been prevented)
Use jQuery. You need to capture the click event and then go on to the website.
$("#myHref").on('click', function() {
alert("inside onclick");
window.location = "http://www.google.com";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click me
To achieve this use following html:
Item
<script>
function make(e) {
// ... your function code
// e.preventDefault(); // use this to NOT go to href site
}
</script>
Here is working example.
No jQuery needed.
Some people say using onclick is bad practice...
This example uses pure browser javascript. By default, it appears that the click handler will evaluate before the navigation, so you can cancel the navigation and do your own if you wish.
<a id="myButton" href="http://google.com">Click me!</a>
<script>
window.addEventListener("load", () => {
document.querySelector("#myButton").addEventListener("click", e => {
alert("Clicked!");
// Can also cancel the event and manually navigate
// e.preventDefault();
// window.location = e.target.href;
});
});
</script>
Use a <button> instead. In general, you should only use a hyperlink for navigation to a real URL.
We can style a button to look like an anchor element.
From https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#onclick_events
Anchor elements are often abused as fake buttons by setting their href to # or javascript:void(0) to prevent the page from refreshing, then listening for their click events .
These bogus href values cause unexpected behavior when copying/dragging links, opening links in a new tab/window, bookmarking, or when JavaScript is loading, errors, or is disabled. They also convey incorrect semantics to assistive technologies, like screen readers.
Use ng-click in place of onclick. and its as simple as that:
Item
<script type="text/javascript">
function theFunction () {
// return true or false, depending on whether you want to allow
// the`href` property to follow through or not
}
</script>

Why i can not trigger the jquery function?

This is a button to close the click but it fail and not work. I would like to know what is the tab ID since i did not think i assign one when i create a tab.
Thank you.
This is my attempt
js
$("#closeTab").click(function() {
window.parent.$('#tt').tabs('close','Create List');
});
html
<input type="button" id="closeTab" value="Cancel" class="submit"/>
I found my js code is working but the button can not trigger it? Why? thank you
latest try:
<script>
$(document).ready(function(){
$("#addlist").validate();
});
$(function(){
$("#closeTab").click(function() {
window.parent.$('#tt').tabs('close','Create List');
});
});
</script>
It still doesn't work so i think it is because the upper function ? How to fix this?
================================================================================
Also, are there any ways to clear my session in using this jquery function (what should i add for instance)?**Thanks
With javascript, you have to delay the execution of certain functions (like event handlers) until the page loads fully. Otherwise, it is attempting to bind a function to an element that doesn't yet exist. With jQuery, you can pass a function to jQuery to be executed on page load very easily like this:
$(function(){ /* code goes here */ });
So to use this with your code, you would do this:
$(function(){
$("#closeTab").click(function() {
window.parent.$('#tt').tabs('close','Create List');
});
});
This way, when the jQuery attempts to bind the function to #closeTab, it happens after the page has loaded (and after #closeTab exists).
Do you have any errors in the console?
Do you include jQuery before that click binding?
Try changing the window.parent.... to alert('clicked!'); and make sure you're actually getting there.
Also, make sure the click binding is inside of a:
$(document).ready(function(){
// here
});
A script can close only the windows it creates. It cannot close the tab which it didn't create.
To rephrase, cannot close tab only if unless but when created tab by script which is same that close window.
I hope this makes sense.
Maybe the form is submitted and the browser navigates to another URL before the code could run? Try replacing function() with function(e) and adding e.preventDefault(); to the beginning of the event handler.

Is there a [universal] way to invoke a default action after calling event.preventDefault()?

This question is for the purposes of developing jQuery plugins and other self-contained JavaScript snippets that don't require modifying other script files for compatibility.
We all know that event.preventDefault() will prevent the default event so we can run a custom function. But what if we want to simply delay the default event before invoking it? I've seen various, case-specific ninja tricks and workarounds to re-invoke the default action, but like I said, my interest is in a universal way to re-trigger the default, and not deal with default triggers on a case-by-case basis.
$(submitButton).click(function (e) {
e.preventDefault();
// Do custom code here.
e.invokeDefault(); // Imaginary... :(
});
Even for something as simple as form submission, there seems to be no universal answer. The $(selector).closest("form").submit() workaround assumes that the default action is a standard form submission, and not something wacky like a __doPostBack() function in ASP.NET. To the end of invoking ASP.NET callbacks, this is the closest I've come to a universal, set-it-and-forget-it solution:
$(submitButton).click(function (e) {
e.preventDefault();
// Do custom code here.
var javascriptCommand = e.currentTarget.attributes.href.nodeValue;
evalLinkJs(javascriptCommand);
});
function evalLinkJs(link) {
// Eat it, Crockford. :)
eval(link.replace(/^javascript:/g, ""));
}
I suppose I could start writing special cases to handle normal links with a window.location redirect, but then we're opening a whole new can of worms--piling on more and more cases for default event invocation creates more problems than solutions.
So how about it? Who has the magic bullet that I've been searching for?
Don't call preventDefault() in the first place. Then the default action will happen after your event handler.
Take a look at this one:
You could try
if(!event.mySecretVariableName) {
event.preventDefault();
} else {
return; // do nothing, let the event go
}
// your handling code goes here
event.originalEvent.mySecretVariableName = "i handled it";
if (document.createEvent) {
this.dispatchEvent(event.originalEvent);
} else {
this.fireEvent(event.originalEvent.eventType, event.originalEvent);
}
Using this answer: How to trigger event in JavaScript? and the jQuery event reference: http://api.jquery.com/category/events/event-object/
Tag the event object you receive so if you receive it again you don't loop.
This should work. I've only tested in firefox though.
<html>
<head>
<script>
window.addEventListener("click",handleClick,false);
function handleClick(e){
if (e.useDefault != true){
alert("we're preventing");
e.preventDefault();
alert(e.screenX);
//Firing the regular action
var evt = document.createEvent("HTMLEvents");
evt.initEvent(e.type,e.bubbles,e.cancelable);
evt["useDefault"] = true;
//Add other "e" attributes like screenX, pageX, etc...
this.dispatchEvent(evt);
}
else{
alert("we're not preventing");
}
}
</script>
</head>
<body>
</body>
</html>
Of course, you'd have to copy over all the old event variables attributes too. I just didn't code that part, but it should be easy enough.
It's not possible like JamWaffles has already proven. Simple explanation why it's impossible: if you re-trigger the default action your event listener intercept again and you have an infinite loop.
And this
click(function (e) {
e.preventDefault();
// Do custom code here.
e.invokeDefault(); // Imaginary... :(
});
is the same like this (with your imaginary function).
click(function (e) {
// Do custom code here.
});
It seems that you want to manipulate the url of your clicked element. If you do it like this it just works fine. Example.
I needed to disable a button after click and then fire the default event, this is my solution
$(document).on('click', '.disabled-after-submit', function(event) {
event.preventDefault();
$(event.currentTarget).addClass('disabled');
$(event.currentTarget).removeClass('disabled-after-submit');
$(event.currentTarget).click();
$(event.currentTarget).prop('disabled', true);
});

Categories

Resources