Skip to content

Instantly share code, notes, and snippets.

@davemyb
davemyb / Add class when position-sticky is activated.md
Last active February 4, 2023 20:56
Add a class to a sticky element when it actually sticks.

How to add a class to an element when it becomes position: sticky, in Drupal.

The code below will add a class to the position:sticky element when it intersects with the assigned element (in the last line of the code). Depending on your HTML structure, you might have to try different elements to target. In this example, the sticky navbar is a direct sibling - this is usually the best way to make this work. I couldn't get this to work if I targeted .site-header.

You can also remove all the Drupal wrapper js code, and just use the code between the "=====" lines, if you're not in Drupal.

<header class="site-header"></header>
<main>
  <div class="wrapper">
@davemyb
davemyb / preprocess_views_view_field.php
Last active October 14, 2022 15:59
Preprocess Views Fields
// Preprocess a field and get a value from another field in the View.
function hook_preprocess_views_view_field(&$variables) {
$view = $variables['view'];
$field = $variables['field'];
$row = $variables['row'];
if ($field->field === MAIN_FIELD_ID) {
// We need to get a value from another field.
foreach ($view->field as $field_id => $field_object) {
if ($other_field_id == OTHER_FIELD_ID) {
@davemyb
davemyb / Drupal8-9_preprocess_snippets.php
Last active March 12, 2022 15:55
Preprocess snippets for Drupal
<?php
// Get image url from a node/term/user
// -----------------------------------
$node = $variables['node'];
// Drupal 8/9 < 9.3. file_create_url is deprecated in 9.3 and removed in 10.
$variables['image_url'] = file_create_url($node->field_image->entity->getFileUri());
// Drupal 9 > 9.3, 10
$variables['image_url'] = $node->field_image->entity->createFileUrl(); // Gives relative path.
$variables['image_url'] = $node->field_image->entity->createFileUrl(FALSE); // Gives full path with domain.