I have a <a href="someaddress"> link that also has a onclick function under a parent <div> with id of "mention". How can I make it so that by default, when user clicks the <a> link it will not redirect to the webpage but it will do the onclick function?
I want to still have href because in case if user's javascript doesn't work, at least they can still go to the link.
...or return false; on your javascript call.
insert e.preventDefault() into your onclick function if it already exists, e.g.
$("#mention a").click(function(e) {
e.preventDefault();
// whatever is not default
});
You could also use return false;.
onclick="return false;" is a way to make an <a> tag not actually do anything on click.
EDIT
i had onlick, obv. it was supposed to be onclick
Use event.preventDefault().
Here's an example: http://jsfiddle.net/FishBasketGordo/2R2Ud/.
Related
I am having this button in an <a> tag (would like to keep it in an a tag).
<center>Change Password</center>
The problem is that when I hit Enter the password gets changed, unfortunately the page reloads, which would be very annoying, when it comes to UX. So, how can I fix this?
EDIT:
Well, I figuered out, that the problem is not the button, but the input.
Here the code:
<div id="login-box-field"><input type="password" id="new_password" placeholder="Password: " class="form-login myLink" title="Password" maxlength="20">
</div>
Well, some people say something about a Form and a JS script. Please, could you tell me, how to do that? Some other samples on the platform here didn't work :(
To prevent the reload of the page, you can use e.preventDefault() inside your function.
Check this out: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Example:
My HTML:
Click me
JS code:
var myLink = document.querySelector('.myLink')
myLink.addEventListener('click', function(e) {
e.preventDefault()
})
Replace anchor tag with button and add onclick() event then call the change passwaord method then it will work fine!
<div>
<center><button onclick="changePassword()" id="box_button" class="pw-button">Change Password</button></center></div>
<script>
function changePassword() {
alert("your code goes here")
}</script>
fiddle is here
you can use jquery prevent default action of a (if you don't want change your html) :
$("a").click(function(event){
event.preventDefault();
});
Update : if clicking password input result is page refresh, then you need to edit that function which this input calls , so edit that function to return false.
You need to prevent the default action of the link with event.preventDefault(). To prevent the link from doing anything, you should omit the href attribute or give it a href of javascript:void(0) or equivalently javascript:; and use the onClick event handler to perform the logic.
<center>Change Password</center>
<script>
function changePassword(e){
e.preventDefault();
console.log("Changing password");
//other logic
}
</script>
everyone.
I've found the solution, which worked for me:
<input class="tableInput" type="text" value="Table input" onkeypress="return tableInputKeyPress(event)" />
<script type="text/javascript">
function tableInputKeyPress(e){
e=e||window.event;
var key = e.keyCode;
if(key==13) //Enter
{
//do you task here...
return true; //return true to submit, false to do nothing
}
}
</script>
Again, thank you very much to everybody who posted his solution :)
I am trying to create a dynamic hyperlink that will download an image retrieved from the server.
The code I am using:
HTML:
<a class="btn" id="controlDownloadJPEG" download>Save & Download</a>
JS:
this.downloadJPEGClickHandler = function() {
CollageCore.downloadJPEG(function(data){
$("#controlDownloadJPEG").attr("href", "../file/fileStore.action?fileName=/" + data[0].AttachmentUrl);
});;
return true;
};
The href is getting changed on click, but the link itself is linking to the href set before my JavaScript executes. The first click does nothing as there is no default href and the second click will download what the first click should have downloaded.
I have seen suggestions to use JavaScript window.href instead of relying on the html tag itself. The reason I need to use the html tag is for its download functionality.
You are treating an asynchronous call as it it is synchronous. It is like ordering a delivery pizza and expecting it to be there as soon as you place the order. That does not happen unless you are standing in the restaurant and it is already been made.
You need to cancel the click and fire the page change manually when the call comes back. So you want to use window.location.href = "new path"; instead of setting the href.
this.downloadJPEGClickHandler = function() {
CollageCore.downloadJPEG(function(data){
window.location.href = "../file/fileStore.action?fileName=/" + data[0].AttachmentUrl;
});
return false; //or preventDefault if you pass in event object
};
If you are are attaching this activity to an onClick(event) handler you should be able to stop the redirect by passing in event.preventDefault();
cite: http://api.jquery.com/event.preventdefault/
Prevent the default click behavior, change the href attribute, and then imitate the click. Should work.
$( "a" ).click(function( event ) {
event.preventDefault();
$("#controlDownloadJPEG").attr("href", "../file/fileStore.action?fileName=/" + data[0].AttachmentUrl);
$(this).click();
});
I have a code similar to this:
<a href='link.html'>goto link page <img src='images/edit.gif' alt='Dont Go, just edit' onclick='doEdit()'></a>
Now I want the href link to work as normal if you click on the text, but if you click on the image, it should do something else and not goto the link at all.
There is also a restriction, I cannot edit the link or its text, the only thing that I have total control over is the img tag and its called onclick function. So I have to prevent the link from going on from within that img tag.
Any help will be appreciated.
Just preventDefault on the click event when the target is an <img>
yourAnchor.addEventListener('click', function (e) {
if (e.target.tagName === 'IMG')
e.preventDefault();
});
Now I want the href link to work as normal if you click on the text, but if you click on the image, it should do something else and not goto the link at all.
The correct way to do that is to not put the img inside the link.
However, if you really want to do that, change your onclick to:
onclick='doEdit(event)'
...and in doEdit:
function doEdit(event) {
if (event.stopPropagation) {
event.stopPropagation(); // Standard
}
else {
event.cancelBubble = true; // Old IE
}
// ...your img logic...
}
That will prevent the click event from bubbling to the link. You need the test for stopPropagation because IE8 and earlier don't have it (or preventDefault), they use properties instead (cancelBubble = true for stopPropagation and returnValue = false for preventDefault). (We're probably stuck with IE8 at least another year, maybe more, despite XP end-of-life...)
Pass the event through to the doEvent method call, similar to this:
<a href='link.html'>goto link page <img src='images/edit.gif' alt='Dont Go, just edit' onclick='doEdit(event)'></a>
Then you can call event.preventDefault() to cancel the event and do your own thing, similar to this:
function doEdit(event){
// your code here
event.preventDefault();
}
DEMO - Using the event object to cancel the event.
Im not quite sure what you mean but if you want the text to have a link and the image to have a onclick event
text
<a href='link.html'>goto link page</a>
image
<img src='images/edit.gif' alt='Dont Go, just edit' onclick='doEdit()'></img>
My initial thought is to simply remove the image tag from between the link tags.
<a href='link.html'>goto link page</a>
<img src='images/edit.gif' alt='Dont Go, just edit' onclick='doEdit()'/>
Are there more restrictions that do not allow you to do something like this?
I have a menu on my aspx page which looks beautiful. It's exactly what I need (found it here).
Problem that I have is this: I need (somehow) to kick off a button control from the javascript. I realize that in the example, the menu items are simply href links, but I'm wondering how I could possibly do a postback and kick off my Button1_OnClick event.
Any ideas?
Thanks,
Jason
Please note that Button1 is an ASP button, with server-side VB.NET code behind it
You'll need something like
__doPostBack(*Button1's clientId*,"OnClick") ;
Button1 will have a property called "ClientID". You can echo that out to the HTML code to get the object by document.getElementById("<%= Button1.ClientID %>"), and from there you only have to invoke the click like normally.
So:
document.getElementById("<%= Button1.ClientID %>").click();
As noted by a commentator, the .click() method won't work in all browsers. Here is one another way to click a button in JavaScript (should also work with links):
// Where 'button' is the value of the document.getElementById() function:
if (button.dispatchEvent) {
var e = document.createEvent(“MouseEvents”);
e.initEvent(“click”, true, true);
button.dispatchEvent(e);
}
else {
button.click();
}
The click() method of any <a> element simulates a click.
You could make your <a /> links, LinkButtons. You could alternativly keep your <a /> links and put runat="server" on them and that would do it without having to fire a separate button click.
I just want to enable / disable onclick and href on elements (a or div).
I don't know how to do this.
I can disable onclick by adding an handler on click event, but the href is still available.
$(this).unbind().click(function(event){
event.preventDefault();
return;
});
Edit FOUND A HACK FOR A ELEMENTS
if ($(this).attr("href")) {
$(this).attr("x-href", $(this).attr("href"));
$(this).removeAttr("href");
}
If you return false on the onclick event, the href is irgnored.
This will go to Goole: <a
href="http://www.google.com"
onclick="alert('Go to
Google')">Test</a>
This will not go to Google: Test
Ok i've found a workaround : putting an overlay over the main div containing all the elements i wanted to disable ..
It just works.
You could try the following:
$('a, div').click(
function(e){
return false;
// cancels default action *and* stops propagation
// or e.preventDefault;
// cancels default action without stopping propagation
});
MDC documentation for preventDefault, jQuery documentation for event.preventDefault.
SO question: JavaScript event.preventDefault vs return false.
I'm unsure as to the problem of the "href still being available," since the click event is cancelled; however if you want to remove the href from a elements:
$('a[href]').attr('href','#');
will remove them (or, rather, replace the URL with a #).
Edited in response to comment (to question) by OP:
Ok, sorry ;) I just want to be able (by clicking on a button), to disable / enable all the links (click or href) over elements (div or a)
$('#buttonRemoveClickId, .buttonClassName').click(
function() {
$('a, div').unbind('click');
});
$('#buttonReplaceClickId, .buttonOtherClassName').click(
function() {
$('a, div').bind('click');
});
unbind(),
bind().
Try this to disable click:
$(this).unbind('click');
You can set the href attribute directly to "" to prevent the original from showing up in the status bar, if that's what you're asking.
$(this).unbind().click(function(event){
event.preventDefault();
}).attr("href", "");
Otherwise, a event.preventDefault() already stops links from being clickable.