2

I have a situation where I am dynamically adding some content to popup box (which is a div) on my page from c#

HtmlGenericControl content = new HtmlGenericControl();
content.InnerHtml = "<a id='close' href='' onclick='action()'>close</a><span>Some text here</span>";
divcontrl.Controls.Add(content);
divcontrl.Attributes.Add("class", "myclass");



javascript method:

function action() {
       $('.myclass').hide();
    }

If I keep href='' on anchor it's closing the window but reloading the page, if I remove it not closing the window.

Jon Adams
  • 24,464
  • 18
  • 82
  • 120
Tiger
  • 417
  • 2
  • 8
  • 23

4 Answers4

4

Change your link tag attr as below,

//Edit changed from href="#" as it will scroll you to the top
href="javascript:void(0);" onclick='return action()' 

And add return to the js function,

function action() {
    $('.myclass').hide();
    return false;
}
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
  • Thanks, This one works, I forgot to mention "return" in event onclick='return action()' – Tiger Jan 25 '12 at 17:36
2

Add return false; at the last line of action() function. This will prevent the default link action - reloading the page (in your case empty href means "the same URL").

Add. Also change onclick="action()" to onclick="return action()". Or onclick="action(); return false;".

gdoron
  • 147,333
  • 58
  • 291
  • 367
Olegas
  • 10,349
  • 8
  • 51
  • 72
1

Use <a href="#" .... or <a href="javascript:void(0);" ...>.

We already know that <a href="#foo">Foo</a> would create a link to an element in the same page with ID as 'foo'. #foo in this case is called a fragment identifier. Clicking it would cause the browser to "jump" to that element in the page without reloading it.

When the fragment identifier doesn't mention the ID of any element in the page (e.g. <a href="#">Foo</a>), then the browser jumps to the top of the page.

Susam Pal
  • 32,765
  • 12
  • 81
  • 103
1
function action() {
       $('.myclass').hide();
       return false;
    }

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

Community
  • 1
  • 1
Shyju
  • 214,206
  • 104
  • 411
  • 497