Ad

Hide Elements Based On Data Atributte JQuery

- 1 answer

I'm trying to write a basic PHP script that will fetch my own Instagram photos and only display the ones I want based on the hashtags I've added to them.

So far based on some tutorials and my self-taught PHP and JS I came up with this:

<html>
<head>
        <script src="assets/js/jquery.min.js"></script>
</head>
<?php

    <html>
    <head>
            <script src="assets/js/jquery.min.js"></script>
    </head>
    <?php

      function fetchData($url){
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      function fetchData($url){
      function fetchData($url){
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_TIMEOUT, 20);
      $result = curl_exec($ch);
      curl_close($ch);
      return $result;
      }

      $result = fetchData("https://api.instagram.com/v1/users/1013397/media/recent/?access_token=1013397.ab103e5.5061b21c8fb0436bb20d881d46f9ae5c&count=14");


      $result = json_decode($result);
      foreach ($result->data as $post) {
         if(empty($post->caption->text)) {
           // Do Nothing
         }
         else {
            echo '
            <div data-tag="'.$post->caption->text.'">
                    <a class="instagram-unit" target="blank" target="_blank" rel="nofollow noreferrer" href="'.$post->link.'">
                            <img data-tag="'.$post->caption->text.'" class="gallery-item" src="'.$post->images->standard_resolution->url.'" alt="'.$post->caption->text.'" width="100%" height="auto" />
                    </a>
            </div>';
         }

      }
    ?>
    <script>
    $(document).ready(function(){
            var permit = '#aruba'
            $('div').each(function(){
            if($('div').attr('data-tag').indexOf(permit) > -1 ){
                    console.log('has tag')
            }
            });
    });
    </script>

I'm trying to hide all the images that don't have the hashtag writen in the JS bar. But so far no luck.

What am I doing wrong?

Ad

Answer

$(document).ready(function(){
    //find all divs, filter out any who do have the matching tag, hide all that don't
    $('div').filter(function(){ return $(this).data('tag') !== "#aruba"; }).hide();
});

Talking about your original issue, part of your issue is your doing an each() over the divs, but then inside there your looking them all up again so you lost context of which one you were actually evaluating which could have been accessed with 'this' or '$(this)'.

Also when working with data elements, use data() and leave off the 'data-' part of the key.

Ad
source: stackoverflow.com
Ad