I'm having trouble with some script interfering with my basic href links and not allowing them to open on left click.
My url is http://www.mayabdesign.com, and on each specific project page (like http://www.mayabdesign.com/#cbp=ajax/sculptjax.html) the "view the site" button does nothing unless you right click and open in a new tab. I know the problem, but can't seem to figure out the solution.
Thanks in advance. :)
Add click function to Dom Ready
$(document).ready(function(){
$("a").click(function( event ) {
if ( $(this).attr("href").match("#") ) {
event.preventDefault();
var href = $(this).attr('href').replace('#', '')
scrollToAnchor( href );
});
});
CHECK DEMO HERE
I think the click events are blocked somewhere with event.preventDefault()
This is the relevent code that is preventing the link from returning. Since the href value does in fact math # its default action is prevented
$("a").click(function( event ) {
if ( $(this).attr("href").match("#") ) {
event.preventDefault();
var href = $(this).attr('href').replace('#', '')
scrollToAnchor( href );
});
Related
I am trying to convert an old "button" to be implemented through an anchor tag. The "button" is actually comprised of a depreciated underline tag:
<u class="hoverable">Browse</u>
My idea was to change change it to an anchor tag by calling a javascript function in the href attribute where "something()" calls whatever click() did previously:
<a class="hoverable" href="javascript:something();">Browse</a>
However,
1) I am not sure if this is the best way to do it
2) Now, using "click()" as the function does nothing
I tried to use the chrome debugger tools and pause the execution when I click the original button, but all the call-stack says is "r.handle" and points to a long line of code that looks like gibberish.
Does anyone know how to set the anchor tag button to call what the underline tag "button" originally did?
Edit: I am trying to fix this code written a while ago by someone else so I am not entirely familiar with it. The part of the page it resides in is
When you click the underlined "Browse" text, a popup window opens that allows you to upload a file. However because it is just an underlined text element that is assigned a class, it is not focusable or accessible by keyboard. My task is to make it accessible by keyboard and use something other than the tag.
The javascript code behind the class hoverable is:
this._hoverable( this.buttonElement );
this.buttonElement
.addClass( baseClasses )
.attr( "role", "button" )
.bind( "mouseenter" + this.eventNamespace, function() {
if ( options.disabled ) {
return;
}
if ( this === lastActive ) {
$( this ).addClass( "ui-state-active" );
}
})
.bind( "mouseleave" + this.eventNamespace, function() {
if ( options.disabled ) {
return;
}
$( this ).removeClass( activeClass );
})
.bind( "click" + this.eventNamespace, function( event ) {
if ( options.disabled ) {
event.preventDefault();
event.stopImmediatePropagation();
}
});
The file base behind this website is massive and somewhat convoluted. I am pretty new to the project and not really that familiar with it yet, so am trying to avoid making many backend changes if I can.
You can add the click event listener to all a elements as follows. You need to make sure you have the last two lines of e.preventDefault() and return false; to ensure the page does not navigate away. This does not use href at all, but I should note that if you omit href entirely, instead of setting it to an empty string, the hyperlink will not appear highlighted.
//get all A elements
var tags = document.getElementsByTagName('a');
//add the event listener to each element
for (let i=0; i<tags.length; i++) {
tags[i].addEventListener("click",function(e) {
document.getElementById('par').style.display = "block";
//these two are needed to prevent the browser from navigating away from the page
e.preventDefault();
return false;
});
}
#par {
display: none;
}
Click Me to Reveal a Message:
<p id="par">This is how you register a click handler to a hyperlink element.</p>
You can use a anchor combined with label and input of type "file" and hidden. No javascript is involved, the focus is there:
<label for= "file"> <input type="file" hidden id="file">Browse</label>
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();
});
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.
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.
Suppose we have the ff. in a.html:
<script>
function onClick() {
// Do some important stuff and then...
location = "b.html";
}
</script>
Link
Double-clicking on Link will trigger the event-handler onClick. However, the second click in the double-click seems to be interpreted as another click and causes the page to jump to the named anchor. In effect, the location isn't changed.
My questions are:
Is this a browser bug or feature?
Is there a way to work-around this behavior?
You could try
href="javascript:void(0);"
instead
Use window.location = "b.html". location by itself has no special meaning.
The anchor jumping is unrelated. You can disable it by stopping the event.
function onClick(event) {
event.preventDefault();
event.stopPropagation();
}
Link
gshankar is right
Another variant:
<script>
function onClick() {
location = "b.html";
return false;
}
</script>
Link
Or you can point the link at the function and skip the onclick event:
<script>
function onClick() {
location = "b.html";
return false;
}
</script>
Link