I am trying to work out why the following is happening.
I am trying to:
Click an element.
On click, pass a DOM element to a function.
Use this DOM element within the function to create a target ID.
Smooth Scroll to this target ID>
Here is my code:
VARIABLE:
var productListQueryResult = $('#product-list-query-result');
TRIGGER:
scrollToDiv(productListQueryResult);
FUNCTION:
// TO TOP OF ELEMENT
function scrollToDiv(e) {
var el = e.attr('id');
$('html, body').animate({
scrollTop: $("#" + el).offset().top
}, 300);
console.log(el);
}
// END TO TOP OF ELEMENT
RESULT:
jquery.js?ver=1.12.4-wp:2 Uncaught Error: Syntax error, unrecognized expression: '#product-list-query-result'
Although this element is in existence. If I run:
var e = jQuery("#product-list-query-result");
console.log(e);
I get two lines returned:
a.fn.init [div#product-list-query-result, context: document, selector: "#product-list-query-result"]
undefined
I'm unsure as to why I get a second line returned too 'undefined', can anyone explain that too?
Hopefully I have provided enough information, if not please feel free to start a discussion.
Edit
I have also tried:
TRIGGER:
scrollToDiv(productListQueryResult.attr('id'));
FUNCTION:
// TO TOP OF ELEMENT
function scrollToDiv(e) {
var el = "'#" + e + "'";
$('html, body').animate({
scrollTop: $(el).offset().top
}, 300);
console.log(el);
}
// END TO TOP OF ELEMENT
RESULT:
Uncaught Error: Syntax error, unrecognized expression: '#product-list-query-result'
EDIT (SOLUTION):
If passing a variable into the selector you do not require the ""'s.
FUNCTION:
// TO TOP OF ELEMENT
function scrollToDiv(e) {
var el = "#" + e;
$('html, body').animate({
scrollTop: $(el).offset().top
}, 300);
console.log(el);
}
// END TO TOP OF ELEMENT
I am still confused why the first attempt wouldn't have worked, and why the simple test returned an undefined line?