Reputation: 63
I want to call the javacsript function on href if the href has the hash tag id.I need the #table as i am using bootstrap tabs so cannot use javasript:show_create_msg(); here is my code
<a href="#table:show_create_msg();">Table</a>
function show_create_msg()
{
alert("error");
}
Upvotes: 1
Views: 1954
Reputation: 770
You can give your element an id, and attach a click event to it.
I will show you how to do it in a more proper way (using "onclick" inline the element is not a good practice)
Here's an example:
HTML
<a id="myLink" href="#table">Table</a>
jQuery
$('#myLink').on('click',function(){
show_create_msg();
});
or even better:
$('#myLink').on('click',function(){
// your show_create_msg code here
});
If you want to prevent the default link behaviour:
$('#myLink').on('click',function(e){
e.preventDefault();
// your show_create_msg code here
});
If you want to trigger the code only on specific hash value:
$('#myLink').on('click',function(e){
var hash = window.location.hash;
if(hash=='#table'){
// your show_create_msg code here
}
});
If you don't want to use jQuery you can use native javascript code:
document.getElementById('myLink').addEventListener('click',function(e){
// your show_create_msg code here
});
Hope it helps a bit
Upvotes: 0
Reputation: 2460
Add
onclick
event andprevent
the click event, then its doesn't load the page when you click the link.
<a href="#table" onclick="show_create_msg();">Table</a>
<script>
function show_create_msg()
{
alert('is working');
// Do something;
return false;
}
</script>
incase you need to find hash
http://example.com#table
<script>
function show_create_msg()
{
alert('is working');
// Do something;
return false;
}
var hash = window.location.hash;
if(hash == '#table'){
show_create_msg();
}
<script>
Upvotes: 2
Reputation: 21489
If you don't want to change your html source, get functoin name from href
attribute of element and set it to onclick
attribute of it.
var fn = $("a").attr("href").replace("#table:", "");
$("a").attr("onclick", fn)
function show_create_msg(){
console.log("function called");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#table:show_create_msg();">Table</a>
Upvotes: 0
Reputation: 7093
Add onclick
event to this link and then write a JavaScript function that does something:
<a href="#" onclick="show_create_msg();">Table</a>
<script>
function show_create_msg()
{
// Do something;
}
</script>
Upvotes: 0