Right way of triggering a javascript from html - javascript

What is the way for having a graphical component (more precisely a twitter.bootstrap icon) in an html website calling a java script.
One could either make a button and putting the icon on it, but this does not look nice IMHO.
Or one could use the href tag,
<a href="#" name="ad_fav" onclick= CALLFUNCTION> <i
class="icon"></i></a>
But what is the cleanest way of achieving this?
It would also be nice if the icon could change after it was clicked.
How it for example the upvote button in stackoverflow implemented?

Another way:
function myFunc () {
// code here
}
var element = document.getElementsByClassName("icon");
element[0].addEventListener("click", myFunc);

Just make the href of the <a> be 'javascript:', example:
<a href="javascript:alert('hello there! this works!')" name="ad_fav"> <i
class="icon"></i></a>
Replace alert(...) with your function call if you need

You don't have do wrap it with an anchor element:
<img src="[path to twitter.bootstrap icon]" onclick="yourJavaScriptFunction" />

Why wouldn't you use jquery on function?
$(document).on("click", "a.icon", function (e) {
e.preventDefault();
});

Related

Make jquery ignore href

I am trying to append data into a div tag using jquery when there is a click event on a html tag,html and javascript code is below and live example for same is at JSFiddle
HTML
<a class="datafile" href="#">abc</a>
<div id="result2">
</div>
Javascript
$(".datafile").click(function() {
$('#result2').append('Clicked!');
}
When a user clicks on abc I dont want the browser to go to link in href rather it should insert Clicked! in div tag.
What I am doing wrong ? Please help.
Something like this:
$(".datafile").click(function(e) {
$('#result2').append('Loading Log File ...');
// For all modern browsers, prevent default behavior of the click
e.preventDefault();
// Just to be sure, older IE's needs this
return false;
});
You have to prevent the default action of the hyperlink.
$('.datafile').click(function(e) {
e.preventDefault();
//Your code
});
Change the href value from '#' to 'javascript:void(0);'?

what's a better way to write javascript:void(0)?

What's a better or correct way to write the following:
click here
If you're using jQuery, the proper way would be:
html
Link
jQ
$('a').click(function(e){ e.preventDefault(); $('p').show(); });
Just omit the href entirely:
<a onclick ="$('p').show()>click here</a>
Since you're using jQuery, use it at its full potential:
<a id="your-id">click here</a>
<script>
$('#your-id').click(function() {
$('p').show();
});
</script>
Use # and return false in the onclick handler.
return false prevents the URL from being followed. An anchor to # points to the current page, so that it makes sense to open/bookmark the link.
click here
The semantically correct thing to do here is to use a button tag instead of an a tag. It is bad practice to use javascript:void(0) in a link. Shoot, it's bad practice to include any inline JavaScript.
Let it point to an URL which will make the desired element to show up by a server side view technology such as PHP/JSP/ASP so that the link still works for clients who have JS disabled.
E.g. in JSP:
link
<p class="bar ${param.foo != 1 ? 'hide' : ''}">paragraph</p>
with
$(".foo").click(function() {
$(this).next(".bar").show();
return false;
});

HTML anchor tag with Javascript onclick event

On using Google I found that they are using onclick events in anchor tags.
In more option in google header part, it looks like normal a tag, but onclicking it doesn't get redirected but opened a menu. Normally when using
<a href='more.php' onclick='show_more_menu()'>More >>></a>
It usually goes to 'more.php' without firing show_more_menu(), but I have show a menu in that page itself. How to do like google?
If your onclick function returns false the default browser behaviour is cancelled. As such:
<a href='http://www.google.com' onclick='return check()'>check</a>
<script type='text/javascript'>
function check()
{
return false;
}
</script>
Either way, whether google does it or not isn't of much importance. It's cleaner to bind your onclick functions within javascript - this way you separate your HTML from other code.
You can even try below option:
More >>>
From what I understand you do not want to redirect when the link is clicked.
You can do:
<a href='javascript:;' onclick='show_more_menu();'>More ></a>
Use following code to show menu instead go to href addres
function show_more_menu(e) {
if( !confirm(`Go to ${e.target.href} ?`) ) e.preventDefault();
}
More >>>
One more solution that prevents default action even if the javascript function returns any value.
<a href="www.any-website.com" onclick='functionToRun();return false;'>
1) Link to work
<a href="#" onClick={this.setActiveTab}>
...View Full List
</a>
setActiveTab = (e) => {
e.preventDefault();
console.log(e.target);
}

javascript use for getting element

<li class="even">
Click here
</li>
I want to change anchor tag text "Click here" using javascript. How can i accomplish this ?
If you're not constrained to using that exact markup and you're really looking for one of the best ways to do this, start off by giving a unique Id to the element that you're going to change:
Click here
document.getElementById("mylink") will give you that element.
Before manipulating an element on the page, you need to ensure that the document is loaded and ready for manipulation. Avoid using inline JavaScript in attributes. Use the following method to attach a document load handler:
window.onload = function () {
// manipulate the document here
};
So, what you're looking for would be:
window.onload = function () {
document.getElementById("mylink").innerHTML = "Something Else";
};
But, if you're really looking for a better solution, don't hesitate to enter the realm of jQuery:
$(function () {
$("#mylink").html("Something Else");
});
document.getElementsByTagName("a")[0].innerHTML = "Changed click here"; //0 is assuming this is your only link
It'd be better to use an id to access that particular link.
EDIT: I noticed you want this to happen on page load:
<body onload="document.getElementsbyTagName('a')[0].innerHTML = 'Changed text';">
Or you could placed that code in a function somewhere and call the function instead.
<body onload="document.getElementById('mylink').innerHTML='new text';">
<li class="even">
<a id='mylink' href="www.google.com">Click here </a>
</li>
</body>

how to stop # links that call javascript functions from jumping to top of page

How do you I stop my links like this:
<a href="#" onClick="submitComment()">
From jumping to the top of the page after the click?
Many times you'll see people use the onclick attribute, and simply return false at the end of it. While this does work reliably, it's a bit ugly and may make your code-base difficult to manage.
<a href="#" onClick="submitComment(); return false;">
Seperate your HTML from your JavaScript
It's far better for you, and your project if you separate your markup from your scripting.
<a id="submit" href="enableScripts.html">Post Comment</a>
With the above HTML, we can find this element and wire up a handler for when the user clicks on the element. We can do all of this from an external .js file so that our HTML remains nice and clean, free from any scripting:
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", setup, false);
} else if (document.attachEvent) {
document.attachEvent("onreadystatechange", setup);
} else {
document.onload = setup;
}
function setup () {
var submit, submitComment;
submit = document.getElementById("submit");
submitComment = function (e) {
e = e || window.event;
e.preventDefault();
alert("You clicked the link!");
};
if (submit.addEventListener) {
submit.addEventListener("click", submitComment, false);
} else if (submit.attachEvent) {
submit.attachEvent("onclick", submitComment);
} else {
submit["onclick"] = submitComment;
}
}
There's a lot going on in the above code, but let's run over it from 30,000 feet. We start by figuring out how to best setup our code when the browser loads the page up. Ideally we'd like to do this when the DOM is ready.
After a few conditional checks we manage to instruct the browser to run our function after the DOM is prepared (this way our anchor element exists for us to interact with its behavior).
Our setup function gets a reference to this anchor, creates a function that we'll run when the anchor is clicked, and then finds a way to attach that function call to the click event of the anchor - losing your mind yet? This is the madness JavaScript developers have had to deal with for some time now.
With jQuery, this is much easier
Perhaps you've heard of jQuery, and wondered why it is so popular. Let's solve the same problem, but this time with jQuery rather than raw vanilla JavaScript. Assuming the following markup:
<a id="submit" href="enableScripts.html">Post Comment</a>
The only JavaScript we need (thanks to jQuery) is this:
$(function(){
$("#submit").on("click", function(event){
event.preventDefault();
submitComment();
});
});
That's it - that is all it takes. jQuery handles all of the tests to determine, given your browser, what the best way is to do this or that. It takes all of the complicated stuff and moves it out of the way so that you are free to be creative.
Add a return false. I believe that without that the page will reload.
<a href="#" onClick="submitComment(); return false;">
Just return false onClick of Hyperlink
Its will not scroll page up ie it will be still where it is
Unless you need the anchor to actual go somewhere, you don't need to use an "href=" reference at all.
Try just using <a id="stay-put">Submit Comment</a>
Then your javascript would look like this:
$("#stay-put").click(function(){
submitComment();
});
Try using:
Javascript is sweet!
This will anchor the page in the place it is at. I had this same issue and this was a simple and good fix for me.
An other simple way is
Link
Then you could have a separate code with onClick event to the class "action-class" with whatever framework you like or plain JavaScript.
You could use this alternative syntax instead:
<a href="javascript:submitComment()">

Categories