I came across a strange problem with html anchor tags. I have an anchor tag on the html page and on clicking the 'a' tag it is supposed to give me an alert message. It is working well. But, If I append a new 'a' tag using jquery to the html page and on click of that appended 'a' tag is not working. i was able to give href, target blah blah blah to the appending 'a' tag but.. onlick function is not working. Any thoughts ???
Thanks in advance.
In jQuery, you typically use the .click() function on a selector to set the click handler. Note that if multiple items match the selector, multiple items will have the click handler installed.
Here's a trivial code snippet that should do what you want:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<script type="text/javascript">
function addLink(label, msg) {
/* Create link element.
The href="#" makes the link act like a link
(be highlighted, selectable, etc.).
The onClick="return false;" keeps the link from
scrolling the browser to the top of the page.
The onClick is not interfered with by jQuery's
.click() . */
var link = $('' + label + '');
/* Install click handler. */
function clicked_handler() {
alert(msg);
}
link.click(clicked_handler);
/* Add the link to the body. */
$('body').append(link);
}
addLink('Link 1', 'You clicked link 1');
$('body').append('<br/>');
addLink('Link 2', 'You clicked link 2');
</script>
</body>
</html>
Your question is unclear.
I assume that you're adding a click handler to the <a> tags by writing $('a.whatever').click(function() { ... }), then adding new <a> tags to the document.
When you write $(...).click(...), it only adds handlers to the elements that were found by the $(...) at the time you added the handler. It will not apply to any elements you add later.
You're probably looking for jQuery's live method, which will handle an event for all elements that match a selector, no matter when they were created.
For example:
$('a.whatever').live('click', function(e) { ... });
Try using this:
$("a").live("click", function(){
alert("Tadah!");
});
Adding an event works on stuff that is already on the page. If You add something aferwards You have to bind a new click eventto this new thing or use live, which always should be the second option
so instead of doing
$(something).append('<a href="" etc. ');
try something like this
$('<a></a>').attr('href','some url here').bind('click',function(){}).appendTo('body');
Related
I'm Making A Game In Html, And I Need To Link To Another Page When A Key Is Pressed.
I've Tried href And Some Other Things.
My Code Is:
<element onkeypress="Gamestart()">
<script>
function Gamestart() {
Play
}
</script>
Html Never Really Gives People Error Messages, So I Have No Error Messages, But My Code Does Not Work.
You have HTML inside your Javascript function which makes no sense. You would be better using the anchor tag <a> with an onclick attribute to trigger a JavaScript function.
You can use the JavaScript window.open() to open a new page.
Click here
<script>
function myFunction {
window.open("https://your-url-here.com/page");
}
</script>
You can do whatever you want in this function, including changing an image like you mention in the title.
I wonder if someone can guide me on how to remove the url label that appears at the bottom of the page when you hover over an anchor (I wonder if it's even posible). I've googled a lot and didn't find any answers.
Suppose I have
<a href="www.somepage.com" title="The Page">Link< /a>
in the bottom of the page there will appear a tooltip/label showing "www.somepage.com".
Please see here for an example
Thanks in advance!
You can use either Javascript or JQuery.
For example, you can set to A attribute "href=#" and add an attribute url=www.somepage.com something like this:
Link
If you click over this nothing happen.
Now, you need to apply with javascript or JQuery click event. The next example is using JQuery and Javascript:
At the bottom of page's body:
<script>
$('#link').click(function() {
var url = $(this).attr('url');
window.location.href=url;
});
</script>
If I have the following simple code segment:
<div ng-app="myApp">
<a ng-disabled='true' ng-click="value1=123">click me</a>
<button ng-disabled='true' ng-click="value2=123">click me</button>
=={{value1}}==
=={{value2}}==
</div>
As you can see from the fiddle : http://jsfiddle.net/basarat/czVPG/ the button is not clickable and ng-click (which is simply a jquery on('click',function(){}) ) does not execute. However it does execute for the anchor tag.
Is it because disabled is not a valid attribute for an anchor tag?
If it is why does it still trigger the dom click event when a button does not?
Read w3c Link and the-a-element
disable is not valid with anchor tags
instead you can do it by event.preventDefault()
$('a').click(function(event){
event.preventDefault();
});
Disabled is not a valid attribute for the anchor tag. Source : http://dev.w3.org/html5/html-author/#the-a-element
If you don't want to use javascript to disable the anchor (as pruposed in other responses) you can just omit the hrefattribute and the anchor wont work and will even change it's styling.
<a>A disabled anchor</a>
Note: I know my answer doesn't directly talk about the disable attribute but the info might still be useful for the audiance, as it was for me.
no it doesnt work with the a tag you can use the jquery event.preventDefault() referance here
The button is an input type, that's why disable works. Anchors don't work the same.
Try giving your a tag an id and disabling using javascript.
<div ng-app="myApp">
<a id="someid" ng-click="value1=123" >click me</a>
<button ng-disabled='true' ng-click="value2=123">click me</button>
=={{value1}}==
=={{value2}}==</div>
After that can disable the element using js and it should behave as input types do.
function DisableButton() {
var submitButton = document.getElementById("someid");
if (submitButton != null) {
submitButton.setAttribute('disabled', 'disabled');
}
}
Make sure you're getting the right client id of your element.
Removing the href or setting it to '#' when you actually want to disable it is kind of a pain if the anchor is to be enabled later, because you need to reset the href to whatever value it should link to. Instead, I just add a disable attribute to the tag and a click event handler and some css. This way the anchor can easily be seen to be disabled, but if enabled where it would go.
Yes, disabled isn't supported attribute by the anchor tab, but the CSS attribute selector does find it and so does jQuery's. So, while the following solution is a mixed jQuery/javaScipt/CSS, it does provide a somewhat nicer way to disable/enable anchors, which supports dynamically adding/removing the disabled attribute to/from the tag with javaScript. Note that this has only been tested and found to work in Chrome.
<style>
a:disabled, /* This doesn't do anything, but hopefully one day ... */
a[disabled] /* This activates when the disabled attribute is added. */
{
cursor: not-allowed; /* Indicate that the link is not to be click! */
}
</style>
<script>
// Use the same css selectors to find all of the disabled anchors ...
$( 'a:disabled, a[disabled]' )
.click( function( event ) {
//
// Prevent disabled anchors from doing their click action ...
//
// Need to recheck that the anchor is still disabled, because the
// jQuery that initially found this anchor and set this event
// handler doesn't affect the anchor after the event is set.
//
// Is this anchor still disabled?
if( this.hasAttribute( 'disabled' ) ) {
event.preventDefault();
}
} );
</script>
Here is a codePen demo:
https://codepen.io/howardb1/pen/XWrEKzP
Not possible unfortunately.
Another sweet option here is to use CSS! Whack a class on that disabled link!
.disabled {
// Prevent element being interactive / the target of pointer events.
pointer-events: 'none';
// Additional styles to make it 'look' disabled below
opacity: 0.5;
}
More on CSS Pointer events here (MDN Web Docs)
You know those webcams you can control over the internet? When you push the button to go left, it moves to the left.. but nothing else happens on the page.. Thats what I need to create.
I have a page that allows me to control lights in my house. When I click the button, I now have it load the php script (that controls the light) in a separate frame.. but I want to get rid of this. So basically I want to create a link that will call the php in the background, but that link won't do anything to the page its on.
Any ideas?
Use a return false; in the click event:
Not Follow the Link
Explanation
The return value of an event handler determines whether or not the default browser behaviour should take place as well. In the case of clicking on links, this would be following the link, but the difference is most noticeable in form submit handlers, where you can cancel a form submission if the user has made a mistake entering the information.
The modern way of achieving this effect is to call event.preventDefault(), and this is specified in the DOM 2 Events specification.
You will need to use ajax to achieve such a behavior.
Links that don't do anything are basically HTML links where you bind the onclick event to a JavaScript function which returns false. This makes the links "do nothing" but still executes the JavaScript which tells the camera to go left/right.
HTML 5 let's you officially use anchor elements without a href attribute. But I would just bind a Javascript event listener to whatever element your already have. I'd even add these kind of interactive elements themselves to the DOM with Javascript, since they don't serve any purpose if a user has JS disabled.
...
will give you text that looks like a link.
If it's not really a link you may wish to consider a different kind of styling to emphasize the point and so that other underlined links show as links and this shows as something else. All depends on your needs and the situation.
I like jquery...
You will notice that the onclick function returns false. This is to stop the link from working...
<a onclick="do_it(this)" ...
then in your js
function do_it(anchor)
{
jQuery.ajax(
{
url : anchor.get_attribute('href'),
data : {whatever},
type : 'POST',
success : function(data)
{
alert('woo');
}
}
)
return false;
}
Pretty much what I'm doing here is:
So when the anchor is clicked jquery POSTs to the anchor's url. You can include data if you need to. This happens asynchronously so nothing happens on your page until jQuery gets response html(or whatever). If you want to do anything with the response you can get hold of it in the success function.
When the function returns it returns false, thus preventing the anchor from doing it's usual thing.
you talking about the javascript, create a onlick event / function and implement AJAX in specific DIV area
please check this out:
http://www.w3schools.com/ajax/ajax_examples.asp
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
//You need `ajax_info.txt` file with some content
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
You can use the following jquery solution:
HTML:
Move lights to left
JQUERY:
<script type="text/javascript">
$(document).ready(function() {
$('#link1').click(function(e) {
e.preventDefault();
$.ajax( $(this).attr('href') );
});
});
</script>
Can't believe no one has posted this yet. just use javascript void:
some click function
Its one of the oldest tricks in the book!
You need Ajax to retrieve datas from PHP without loading another page.
To "disable" the link:
Link
Or:
Link
Or just write a normal link and use jQuery (or another library) to add the event:
$('a').click(function(event) {
// the code with ajax
event.preventDefault();
});
I was wondering if anyone knew how, when on link submit the page does not move i.e
If it was 2 page lengths down it would shoot up to the top.
If you have attached event to HTML control through jQuery then you can use return false like
$("#myDiv").delegate("tr", "click", function() {
enter code here
return false;
});
No need to replace anchors, as your own answer to the question states.
This will work just as well:
<a href="#" onclick="yourOwnSubmitFunction(); return false;">
In short, just make sure that whatever function is in the onClick handler returns boolean false.
Whilst having the link's onclick handler return false; is the correct way to stop a link being followed, it's a bit of a hack to use a link this way, because what you've got is an action and not a link. You can't do the usual link-like things to your link, like right-click-bookmark, or middle-click-for-new-tab and so on, so it shouldn't really have that affordance.
An alternative (that eg. SO uses) is to put the onclick on a non-link element instead, eg.:
<span id="potato">Do something</span>
<script type="text/javascript">
document.getElementById('potato').onclick= function() {
// do something
};
</script>
This is cleaner, but has a drawback in is that the link can't be focused and activated by the usual keyboard tabbing method.
Arguably better is to use an <input type="button"> or <button type="button">, which are the right markup to represent an action. Of course these look quite different, but you can use CSS to style them so that they look like a link instead of a button if you like. The one drawback of this method is that good old silly IE cannot completely restyle a button; you will get a few pixels of unremovable extra padding in this browser.
If you are using .net 2.0
There is a
MaintainScrollPositionOnPostback
property in #page directive that you can use to maintain the scroll position of the page.
Gets or sets a value indicating
whether to return the user to the same
position in the client browser after
postback. This property replaces the
obsolete SmartNavigation property.
When Web pages are posted back to the
server, the user is returned to the
top of the page. On long Web pages,
this means that the user has to scroll
the page back to the last position on
the page.
When the
MaintainScrollPositionOnPostback()()()
property is set to true, the user is
instead returned to the last position
on the page.
If you can't use this then set location.href to an anchor tag at the specified position after the submit.
location.href = "#anchAtPos";
where anchAtPos is the id of the anchor tag at a specified position.
I solved this using:
function anchorReplace()
{
$("#reportWrapper a").each(function(i){
var anchorElement = $(this);
var newAnchorElement = $('<a href="#link' + i + '" name="#link' + i + '">'
+ anchorElement.text() + '</a>').insertBefore(anchorElement);
anchorElement.remove();
});
}
I've fixed this before by putting
onclick='return false;'
Inside the link
<a href="#" onclick='return false;' id='attachAlistenertothisID'>This link doesn't jump to the top!</a>
I use this for my links that have click listeners attached them via jQuery.
Hope this helps someone!