JQuery href preventdefault issue with anchor - javascript

I have a link as following.
Tab 3
On tab 2, when Tab 3 is clicked, I want to first validate whether form in Tab 2 is correctly filled.
$("#tab3Link").click(function(e){
e.preventDefault();
$("#tab3Link").prop("href", "#");
if(validateTab2()){
$("#tab3Link").prop("href", "#tab3Info");
return true;
}else{
return false;
}
});
#tab3Info anchor should take the page to a new div. But click does not happen. But if I manually append #tab3Info at the end of the URL and press enter, page moves to new tab. So in the above function, although href is changed, click function does not happen.
This is working fine when JQuery 1.4.2 is used with Jquery mobile 1.1.0. Problem occurs when JQuery was upgraded to 1.9.1 and Jquery mobile to 1.3.2.

Usage of jQuery prop() method does not apply since it sets a property in the element (in your case #tab3Link). But you want to manipulate the location value.
Instead of:
$("#tab3Link").prop("href", "#tab3Info");
You can either use:
window.location.hash = 'tab3Info';
or:
window.location += '#tab3Info';

Instead of return true, try:
$(this).unbind('click');
$(this).click();

Related

how to change href during onclick event

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();
});

Event click on href <a> tag [duplicate]

This question already has answers here:
How do I programmatically click a link with javascript?
(12 answers)
Closed 8 years ago.
I have a question about Javascript event here. I have an <a> tag like this:
<a id='aTag' href='http://example.com'>Click to redirect</a>
Then I call an event like:
<script>
$('#aTag').click();
//or
$('#aTag').trigger('click');
</script>
It does not redirect me to http://example.com. I tried to add an onClick() event in the <a> tag like this:
<a id='aTag' href='http://example.com' onclick='alert("Event happened");'>Click to redirect</a>
And then call the .click() event. It shows me alert("Event happened");
Can anyone show me how to call the .click() event correctly, or correct this redirect with issue with the href in that <a> tag?
In my business I just need an <a> tag, so not with the window.open or windown.location.
Explanation
Redirects can only happen if the user clicks directly on the link. Programmatic or deferred click triggers do not work.
An alternative would be:
to change directly the window.location
to open the link in a new tab/window
Changing window.location
window.location="http://wherever.you/want/to/g0";
or
window.location=$('a.selector').attr('href'); // to use a link's address
New tab/window
You cannot programmatically (click() or trigger) open new tabs/ windows or redirect. They get (ad-)blocked. automatically
So new tab/window openings always have to be triggered by user action. (Otherwise we'd always be full with popup ads)
So 1st of all, make sure that your js is executed on a user event, and then you should be able to use window.open.
JsFiddle example
html:
new tab google
<button class="user">user triggered</button>
<button class="programatic">programatic</button>
js:
$('a').on('click', function(e) {
console.log('clicked', e);
// unfortunately although we simulated
// the click on the <a/> , it will still
// not launch a new window - idk why.
// therefore we can use the line below
// to open the <a>'s href in a new tab/window
// NOTE: this will only occur if the execution was
// triggered by the user
window.open(e.currentTarget.href);
});
var simulateClick = function(origEv) {
var e = $.Event("click");
e.ctrlKey = true;
e.metaKey = true;
e.originalEvent = origEv;
$('a').trigger(e);
};
$('button.user').on('click', function(e) {
// this call will actually open a window
simulateClick(e);
});
$('button.programatic').on('click', function(e) {
// this will result in a blocked popup
$.get('/someurl').always(function() {
// executes the method after a non-user event
// results in blocked popup
simulateClick(e);
});
});
// this will result in a blocked popup
setTimeout(simulateClick, 1000);
Try this -
<a id="aTag" href="http://mylink.com" onclick="return doWork();">Click to redirect</a>
<script>
function doWork(){
//... do your works
return true; // then return true to redirect
}
</script>
Here is the fiddle - http://jsfiddle.net/gcJ73/
(Though the fiddle attributes are a little different to show you that it works)
or with jQuery:
//first assign the click handler
$('#aTag').click(function(){
//... do your work
return true;
});
//then call programmatically
$("#aTag").click(); or $("#aTag").trigger("click");
BTW programatically calling it will not redirect. Will just call the event handler, not redirect.
jQuery fiddle - http://jsfiddle.net/gcJ73/3/
Try:
<script>
jQuery('#aTag').click(function() {
// Your Code
});
</script>
jQuery('#aTag').click() does not execute the href attribute of an anchor tag so you will not be redirected, do:
$(document).ready(function() {
jQuery('#aTag').click( function (e) {
window.location.href = this.href;
});
});
<a id='aTag' href='http://mylink.com' onclick="location.href='http://mylink.com';">
Click to redirect
</a>
check this code snippet, also it will work like what you want to do.

JavaScript window #hash actions

I have two links on the page
Form
Image
I made a simple click.
$('a[href="#Form"]').on('click',function(){
alert("hi");
});
also I'd like HASH works as well.
if(window.location.hash = "#Form"){alert("hi");}
Once the page loads, it shows ALERT, then I click Image link, the url becomes www.myweb.com/#Image, if I press (history) button, the url looks www.myweb.com/#Form BUT alert("hi") isn't working anymore.
Can I make it still works even I press button?
You could try something like:
$(window).on('hashchange',function(){
if(document.location.hash == '#Form'){
alert('hi')
}
});
First your condition is wrong:-
if(window.location.hash = "#Form"){alert("hi");}
to
if(window.location.hash == "#Form"){alert("hi");}
Other thing you need to bind hashchange event. Not all browsers support this event. In that case you need to check hash changes using setInterval function of javascript.

Detecting form changes using jQuery when the form changes themselves were triggered by JS

I have a list of radio buttons that I can toggle "yes" or "no" to using Javascript.
$(document).ready(function(){
$('#select-all').click(function(){
$('#notifications .notif-radio').each(function(){
$('input[type="radio"]', this).eq(0).attr('checked', true);
$('input[type="radio"]', this).eq(1).attr('checked', false);
});
});
$('#deselect-all').click(function(){
$('#notifications .notif-radio').each(function(){
$('input[type="radio"]', this).eq(0).attr('checked', false);
$('input[type="radio"]', this).eq(1).attr('checked', true);
});
});
});
this works just fine. Now I have a separate piece of code that detects when a user has changed something, and asks them if they want to leave the page.
var stay_on_page;
window.onbeforeunload = confirm_exit;
$('.container form input[TYPE="SUBMIT"]').click(function(){
stay_on_page = false;
});
$('#wrapper #content .container.edit-user form').change(function(){
stay_on_page = true;
});
function confirm_exit()
{
if(stay_on_page){ return "Are you sure you want to navigate away without saving changes?"; }
}
The problem is that if the user uses the first piece of functionality to toggle all radio buttons one way or another. The JS detecting form changes doesn't see that the form was changed. I have tried using .live, but to no avail. Anyone have any ideas?
I do something similar to this by adding change() (or whatever's appropriate, click() in your case I suppose) event handlers which set either a visible or hidden field value, then check that value as part of your onbeforeunload function.
So, my on before unload looks like:
window.onbeforeunload = function () {
if ($('#dirtymark').length) {
return "You have unsaved changes.";
}
};
And, or course, dirtymark is added to the page (a red asterisk near the Save button), when the page becomes dirty.

Disable (and re-enable) the href and onclick on elements

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.

Categories