I was assigned to work on a web page which has a bunch of buttons on it. Each of those buttons needs to scroll down to a specific div and change the content of it. My problem is, that every time I click, it only ever anchors and never activates the onclick unless I remove the href. How can I make it use BOTH href AND onclick?
Example:
<img src="images/image.png" />
If you return true from onclick it will do the href. If you return false from onclick it will not do the href:
Do Nothing
Do Href
One way would be to do the jump to location also in javascript.
The advantage being that you could choose the sequence in which it happens. In this case, you could show the alert after moving to the new location if you wanted to.
You could write a function like this:
function jumpTo(strLocTag){
window.location.hash = strLocTag;
}
And then modify the HTML like this:
<img src="images/image.png" />
Try to make a function to call with onclick that have both,
so when you click it will do what every you trying to achieve here and then redirect you to the url you are pointing at
window.location.replace("~/Page.aspx#divId");
Also you can use a function to keep your HTML clean
<img src="images/image.png" />
in your javascript file
function extra(){
alert("Test");
window.location.replace("http://stackoverflow.com");
}
If it was me I would just do everything in the onClick method and forget about the href part.
The onClick method can do what you wanted to do in the first place and then after that scroll down to the anchor tag. Here is a function that I wrote using jQuery to smoothly scroll somewhere on the page using an anchor tag. This is how I would use it:
function smoothScroll(anchorName, scrollSpeed) {
// Do whatever you were going to have in the onClick event here
// Start the scrolling to the anchor tag
var gotoAnchor = "a[name='" + anchorName + "']";
var scrollToPoint = $(gotoAnchor).offset().top;
$('html, body').animate({ scrollTop: scrollToPoint }, scrollSpeed);
}
Then to use the function just take out the href of the link and put this function in the onClick event:
<img src="images/image.png" />
Related
How could one trigger the default action/event of a HTML link (anchor element)? That is to use JavaScript/jQuery to "click" an existing HTML link, as if the user has clicked it.
Just using .click() does not seem to work.
$('#alink').click();
// the nothing happening
For this HTML:
<a id="alink" href="http://google.com" target="_blank">a link</a>
Example fiddle: http://jsfiddle.net/dCfD8/
I'd rather not create a new window in JavaScript (and take care of whatever else needs to be handled when a link is clicked).
You can trigger the click event using a simple trigger method in jQuery.
$('#alink').trigger('click');
Beware though, that even in the event gets fired, the browser will not follow the link href. The only way to follow the href is to actually click it with the mouse yourself.
As far as I know, there is no way to force a link to behave as if it were clicked. You have to change the document location or something like that to actually navigate between pages.
Expanding on Fabio Cicerchia's comment to his own post: You can use window.open:
var link = $('#alink');
var target = link.attr("target");
window.open(link.attr("href"), target ? target : "_self");
<script src='jquery lib source' ></script>
<script>
function force()
{ ...do something...to fill page2
$('#gopage2').trigger('submit');
}
</script>
<form action='#page2' id='gopage2'>
</form>
...
<span name='#page2'>This is page2</span>
try this:
$('#alink').trigger('click');
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>
I'm trying to use AJAX loading a set of sucessive pages in a main page, as I show you in the next picture:
I learned (thanks to this community!) to call other pages' content, by assigning the load() function to the onclick event of a button, like this:
$(document).ready(function() {
$('#btn').click(function() {
$('#result').load('./poi-data-no-heading.html');
});
});
But what if I have one button with id="btn" on every page? The functionality of any button with that id will be the same always, because (I think) the document.ready is not triggered when I use the load() method, so it's never replaced with new functionality.
E.g. initial functionality should be navigate from page 1 to page 2, and when page 2 is loaded, the functionality should be to navigate from page 2 to page 3.
As Js developer, I would do the following:
<!-- In the HTML file -->
<button id="btn" onclick="loadContent()">Load</button>
<div id="result"></div>
/* In the JS file */
function loadContent(){
/*the code to retrieve content*/
$('#result').load('http://fiddle.jshell.net/webdevem/JfcJp/show/');
}
This way I could assign the functionality to every button, no matter what's the ID or if the document.ready is triggered. But mixing Js with JQuery is not an option... So, how do you think I should manage to do something similar with JQuery?
Thanks in advance.
P/d: Here is a useful fiddle I used to try ideas: http://jsfiddle.net/gal007/vkcug7t7/1/
You could use the on() event from jQuery, which can listen for events on elements dynamically rendered (you can't do that with the click() method). So in this case you have to listen to the event on a parent element, one that doesn't change with the load method. On that button, use an HTML5 data-* attribute to define the id that you wish to load.
HTML:
<btn id="result" data-load-id="1">Load</btn>
Javascript:
$('#container').on('click', '#result', function() {
var id_to_load = $(this).data('load-id');
load('/url?' + id_to_load);
});
I've updated your fiddle : jsfiddle
This may sound a weird question,
I have a page which has a link:
<a href="#" class="emails" > Email to Friends </a>
Now I have an event attach to the anchor tag so that on click the given div toggle it state.
The Javascript Code look like this:
$(document).ready(function() {
$(".emails").bind("click",function() {
$("div#container").toggle
})
})
Now the above code and all of it works fine,
but here the big deal,
when I click the given link the my focus of the page move to top of the page,
and I have to scroll all the way down to see the change.
Can anyone help me on this?
It does this because the href="#" is an empty anchor. Anchors are used for linking to specific spots within a page. An empty anchor results in the page going back to the top.
To fix this in your javascript, you need to prevent the click event from propagating or "bubbling" up the DOM. You can do this by returning false from your click event.
$(document).ready(function() {
$(".emails").bind("click",function() {
$("div#container").toggle();
return false; // prevent propagation
})
});
You can also make the event available in the bind's click handler function by using an argument, usually named e. Having access to the event allows you to call methods on it such as .preventDefault().
$(document).ready(function() {
$(".emails").bind("click", function(event) {
$("div#container").toggle();
event.preventDefault(); // this can also go at the start of the method if you prefer
})
});
This will solve all cases where anchor is empty.
$(document).ready(function () {
$('a').click(function () {
$('[href = #]');
return false;
});
});
This comes from the href='#' in the a. Just remove this tag. But then it's technically not a link any more, so the cursor will default to a text-selector when over it. You can override this using cursor:pointer in your CSS. See the left menu on this website for reference.
Use:
<a href="javascript:void(0)" class="emails" > Email to Friends </a>
Or, using jQuery,
$(document).ready(function() {
$(".emails").attr("href","javascript:void(0)");
})
Void(0) returns a.. well.. it doesn't return anything. The browser knows how to go to nothing (i.e., what would happen if you did href=""), and to # (# is the top of the page), but not how to go to a void "value".
Whenever you put a javascript: in an attribute, the attribute's value gets set to the return value of the code inside. The code is called the first time the attribute is accessed.
But, void(0) returns nothing. Not even "". The browser takes this to meant that the link is not a link at all.
Simple quick question....
I have the following link html:
<a href="http://www.site.com/" onmouseover="" />
I have a javascript function which I want to enter some onmouseover information into that link dynamically. So, lets say it then becomes this for example if this javascript function is called:
<a href="http://www.site.com/" onmouseover="alert('howdy')" />
any ideas how to do this?
Add name attribute to and assign onmouseover
<a href="http://www.site.com/" onmouseover="" name="xxx"/>
document.getelementsbyname('xxx').onmouseover = function() { alert('howdy') }
Answer was, using setAttribute() javascript.
I think you want to say: dynamically change your href attribute information then you can do it by jquery
//Write code for prompt box and get value (when mouse-over)
$("a[href='http://www.google.com/']").attr('href', 'YOUR_GET_VALUE')
If you can use jquery, see: http://api.jquery.com/hover/
This is better than changing the attribute directly. Your javascript function can dynamically bind/unbind the mouse hover event and execute your alert call.
Otherwise your javascript function will need to dynamically change the attribute but you'll need to work around browser differences to locate the correct element then locate and modify the onmouseover attribute.
two options:
if it's something small:
<a href="http://www.site.com/" onmouseover="this.href = 'http://stackoverflow.com'" />
if you have something more to do:
<script type="text/javascript">
function doSomething(elem) {
elem.href = 'http://stackoverflow.com';
}
</script>
test
Or as stated before: use jQuery or any other framework to make your life a lot easier
The following works for jQuery every time
first the javascript:
$(document).on('mouseenter','.hovLink', function (e) {
e.preventDefault();
e.stopPropagation();
alert('entering ' + e.target.id);
}).on('mouseleave','.hovLink', function (e) {
alert('exiting ' + e.target.id);
});
and here is the HTML
Link