Alireza
Alireza

Reputation: 6868

How to take different approaches based on whether Javascript is enabled or not?

We're using JSON in some parts of our PHP project. The edit part has been programmed by JSON, so the href part contains something like below:

<a href="javascript:void(0);" id="button">Edit</a>

We want to check that if Javascript is disabled then change the URL as follow, because the above link would not work if JS is disabled:

<a href="./edit.php?id=12&text=some_text_here" id="button">Edit</a>

We tried <noscript>, but we gain no success. how to do something like above, we're stuck here.
I appreciate in advance.

Upvotes: 0

Views: 80

Answers (4)

DaveRandom
DaveRandom

Reputation: 88697

You can do something like this:

<a href="./edit.php?id=12&text=some_text_here" id="button">Edit</a>
<script type='text/javascript'>
  // ...or however you assign a click handler to the element
  document.getElementById('button').onclick = function() {
    // Do Javascript stuff here
    return false;
  };
</script>

If you return false from your click handler, the Javascript-enabled browser will not navigate to the link's location. When Javascript is disabled the link will be followed as normal.

Upvotes: 0

Brenton Alker
Brenton Alker

Reputation: 9072

You might want to use what is know as "progressive enhancement". This basically means, you write your HTML as if JavaScript is not enabled, then use JavaScript to enhance the features.

This is usually achieved by attaching events, modifying the DOM etc. within a function that is called on page load.

Upvotes: 1

adrien54
adrien54

Reputation: 1640

Maybe you can build your page normally using the php link href="./edit.php?id=12&text=some_text_here" and when your document is loaded execute a javascript function that will replace the href attribute of the <a> tag with javascript:void(0);

Example of the function with jquery:

$('a.button').attr('href', 'javascript:void(0);');

If the user doesn't have Javascript then the href attribute won't be updated.

Upvotes: 1

Quasipickle
Quasipickle

Reputation: 4498

Default to your non-Javascript state, then use Javascript to cancel the following of the link. Users without Javascript will then follow the link, and those that have it enabled will not.

Upvotes: 8

Related Questions