Question

Good morning everybody,

I'm actually beginning to develop using jQuery and I'd like to do it properly, in a way that's optimized and semantically correct. I wrote a simple example for you to understand where my problem is :

<?php 
$file = 'count.txt';
$count = file_get_contents($file);
$count = (int) $count + 1;
file_put_contents($file, $count);
?>
<html>
  <body>
    <p><?php echo $count; ?></p>
    <a href="" id="hello">Cliquez !</a>
  </body>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script>
    $('#hello').click(function(){
      $(this).hide();
    });
  </script>
</html>

The php script is counting how many times the page was loaded and displays it. The html part contains a < a > link which I wanna hide in jQuery script.

The abovementioned example does not hide the < a >, or we cannot see it hiden, because browser is refreshing the page immediatly after, since href is empty. So, php count is just increasing and < a > is not hiden.

I googled my problem and found that I have to use "return false;" at the end of my script to stop event propagation to the browser. Ok, got it.

But, in fact, "return false;" function is actually containing 2 functions : preventDefault() and stopPropagation(). See this http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/

So, I'd like to know if it's preferable (in a way that's optimized and semantically correct) whether to use a < button > tag instead of a < a > or continue using a < a > tag and replace return false; by preventDefault.

Thank you in advance

Was it helpful?

Solution

You have to supress the default event that is happening on click, that way you can choose eiter button or an a-tag to your own (style?) preference. If its semantically correct also depends on the context ;)

<script>
    $('#hello').click(function(event){
        event.preventDefault();
        $(this).hide();
    });
</script>

Also see: http://www.w3schools.com/jquery/event_preventdefault.asp

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top