Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

Commit

Permalink
Enhance navigation with smooth scroll to specific elements
Browse files Browse the repository at this point in the history
This commit introduces changes to the directive.js and ProductQuery.php files.

In directives.js, the functionality of fetching a page and updating scroll behavior is enhanced. Now, apart from the smooth or default scroll, the function also considers the 'scrollToSelector' property of a link. It calculates the top position of the element (identified by the selector) in the viewport and uses it for scrolling, providing a more precise and user-friendly scrolling experience.

In ProductQuery.php, the navigation link payload is updated to include a 'scrollToSelector' attribute. This attribute uses a data attribute selector that identifies the product block that the navigation link should scroll to.

These enhancements improve user navigation by allowing smooth scrolling to specific product blocks rather than just the top of the page.
  • Loading branch information
imanish003 committed Jul 26, 2023
1 parent 763ddf8 commit 2abadbd
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
18 changes: 16 additions & 2 deletions assets/js/interactivity/directives.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,15 +173,29 @@ export default () => {
// Fetch the page (or return it from cache).
await navigate( href );

// Scroll to the element if it's defined.
let topPosition = 0;
if ( link?.scrollToSelector ) {
const element = document.querySelector(
link?.scrollToSelector
);

if ( element ) {
topPosition =
element.getBoundingClientRect().top +
window.scrollY;
}
}

// Update the scroll, depending on the option. True by default.
if ( link?.scroll === 'smooth' ) {
window.scrollTo( {
top: 0,
top: topPosition,
left: 0,
behavior: 'smooth',
} );
} else if ( link?.scroll !== false ) {
window.scrollTo( 0, 0 );
window.scrollTo( 0, topPosition );
}
};
}
Expand Down
5 changes: 3 additions & 2 deletions src/BlockTypes/ProductQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,9 @@ public function add_navigation_link_directives( $block_content, $block, $instanc
$is_previous_or_next = $is_previous || $is_next;

$navigation_link_payload = array(
'prefetch' => $is_previous_or_next,
'scroll' => true,
'prefetch' => $is_previous_or_next,
'scroll' => true,
'scrollToSelector' => '[data-wc-navigation-id="woo-products-' . $this->parsed_block['attrs']['queryId'] . '"]',
);

$p->set_attribute(
Expand Down

0 comments on commit 2abadbd

Please sign in to comment.