Skip to content

Instantly share code, notes, and snippets.

@thelevicole
Last active February 1, 2021 16:15
Show Gist options
  • Save thelevicole/2f94a72909c32bf9717f23f901e35713 to your computer and use it in GitHub Desktop.
Save thelevicole/2f94a72909c32bf9717f23f901e35713 to your computer and use it in GitHub Desktop.
PHP animate on scroll (AOS) helper function.

Basic usage

<div class="text" <?php aos( 'fade-up' ); ?>>
  ...
</div>

Additional settings

<div class="text" <?php aos( [
  'name' => 'fade-up',
  'anchor-placement' => 'center-center'
] ); ?>>
  ...
</div>

Conditional settings

<?php
  $aos_settings = [
    'name' => 'fade-up',
    'anchor-placement' => !empty( $placement ) ? $placement : null // `null` values removed.
  ];
?>
<div class="text" <?php aos( $aos_settings ); ?>>
  ...
</div>
<?php
/**
* Print/return inline AOS animation attributes.
*
* @param string|array $settings
* @param bool $echo
* @return string|null
*/
function aos( $settings = [], $echo = true ) {
// Set default attribute values here
$detaults = [
'duration' => 4000
];
$data = [];
if ( is_string( $settings ) ) {
$data[ 'name' ] = $settings;
} else if ( is_array( $settings ) ) {
$data = $settings;
}
// Merge defaults
$data = array_merge( $detaults, $data );
// Cleaned data
$cleaned = [];
// Clean and remove duplicates
foreach ( $data as $key => $value ) {
// Remove prepending data-aos- and aos-
$key = strtolower( $key );
$key = preg_replace( '/^data-aos|^aos/', '', $key );
$key = ltrim( $key, '-' );
$key = '-' . $key;
// Remove key if is name
if ( $key === '-name' ) {
$key = '';
}
$key = 'data-aos' . $key;
// Overrides previous value if exists
$cleaned[ $key ] = $value;
}
// Remove empty values
$cleaned = array_filter( $cleaned );
// Join key values for HTML
$values = array_map( function( $key, $value ) {
return $key . '="' . $value . '"';
}, array_keys( $cleaned ), array_values( $cleaned ) );
// Create html stirng
$html = implode( ' ', $values );
if ( $echo ) {
if ( trim( $html ) ) {
echo $html;
}
} else {
return $html;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment