1

I'm trying to dynamically add and remove the attribute hidden to some HTML elements with the following code:

<li><a href="#" onclick="SelectImage( 5 ); return false;">6</a></li>
...
<a href="/image/5"><img class="image_to_be_selected" id="image_5" hidden src="/img/5.jpg"></a>
<script type="text/javascript">
  $('#image_0').removeAttr( 'hidden' );
  function SelectImage( no ) {
    $('.image_to_be_selected').prop( 'hidden' );
    $('#image_'+no).removeAttr( 'hidden' );
  }
</script>

Main idea of this code is to remove the attribute 'hidden' from the first image at the beginning and upon <li> click hide all images and than to remove the property 'hidden' from the selected image.

But the code is not working properly: $().prop() doesn't add the attribute as desired. I should use $().attr('hidden',true) instead, but in this case the HTML will become as:

<a href="/image/5"><img class="image_to_be_selected" id="image_5" hidden='hidden' src="/img/5.jpg"></a>

(with extra ='hidden' chars)

Is it correct from the HTML validity POV? Is there any function in JQuery to add an attribute with no value?

Roman Matveev
  • 563
  • 1
  • 6
  • 22
  • 1
    `hidden` is not a [global attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes?redirectlocale=en-US&redirectslug=HTML%2FGlobal_attributes), and is usually used with input-elements, not images. You should consider using the `data-*` attributes instead, if you need to keep this information as an attribute. Something like `data-hidden="true"`. If the attribute is used solely for styling purposes, consider making it a class instead. – Christofer Eliasson Jan 22 '14 at 14:44

3 Answers3

3

Instead of adding and removing the hidden attribute, why not use jQuery .show() and .hide() instead?

$('#image_0').show();
  function SelectImage( no ) {
    $('.image_to_be_selected').hide();
    $('#image_'+no).show();
}
RobF
  • 2,758
  • 1
  • 20
  • 25
1

An alternative way is to use jquery show() and hide() to the elements of your choice.

$('#elementID').show();
dansv130
  • 317
  • 1
  • 3
  • 12
1

Your using prop() wrong. prop('string') is the getter prop('string', value) is the setter. You're using the getter and expecting it to set the value.

so

$('a').prop('hidden', true);

does

<a href="/image/5"><img class="image_to_be_selected" id="image_5" hidden src="/img/5.jpg"></a>

and

$('a').prop('hidden', false);

results in

<a href="/image/5"><img class="image_to_be_selected" id="image_5" src="/img/5.jpg"></a>

API docs here

Changing your code to:

$('#image_0').prop('hidden', true);
  function SelectImage( no ) {
    $('.image_to_be_selected').prop('hidden',  true);
    $('#image_'+no).prop('hidden', false);
  }

should result in the desired effect

Or do as Wbas says.....

Liam
  • 27,717
  • 28
  • 128
  • 190