user1156544 February 2016

Jquery Using external URIs as IDs for scrolling

I know this is a basic question. I have the following structure:

 <li id="example.org/element1"></li>
 <li id="http://example.org/element2"></li>
 <li id="example"></li>

I am trying to scroll to their positions when clicking certain elements. The function that scrolls is as follows:

var target = ...
  console.log(target);
  $('html,body').animate({
    scrollTop: $('#' + target).offset().top
  }, 1000);

This is working fine with the ID "example", but not with the other universal IDs containing URIs:

example.org/element1
jquery-2.2.0.min.js:2 Uncaught Error: Syntax error, unrecognized expression: #example.org/element1


http://example.org/element2
jquery-2.2.0.min.js:2 Uncaught Error: Syntax error, unrecognized expression: #http://example.org/element2

I have been researching and tried options such as escaping characters and others, but nothing worked. Is there a way I can use internally such IDs?

Answers


Gavriel February 2016

Use data-id, instead of id, because I'm not sure what can be in id:

<li data-id="example.org/element1">1</li>

and:

$('[data-id="' + target + '"]')

Make sure it's properly escaped in case it has single or double quotes in the string


gurvinder372 February 2016

This is working fine with the ID "example", but not with the other universal IDs containing URIs:

because your code scrollTop: $('#' + target).offset().top is looking for a valid element selector with an id, not just any URL.

In case of <li id="example.org/element1"></li>, your jquery code translates to

scrollTop: $('#example.org/element1').offset().top

which is not the valid id of the element.

However, you can make it a different attribute (something like data-id like @Gavriel has mentioned)

<li data-id="example.org/element1">1</li>


console.log( $( "li[data-id='example.org/element1']" ).html() );

Post Status

Asked in February 2016
Viewed 3,110 times
Voted 8
Answered 2 times

Search




Leave an answer