Support » Developing with WordPress » Help using javascript in archive loop

  • Resolved unsavouryindividual

    (@unsavouryindividual)


    Hi folks,
    I’m a complete beginner with Javascript. I know there is a way of doing this.

    I have a custom archive page. I echo the thumbnail URL in an invisible div on each item. I put that URL into a javascript variable with a function. When user clicks a button, the function executes and it injects the URL into the src of an tag outside of the loop.

    This works great, except I need to iterate the name of my JS functions as well as the id names so the first posts thumbnail isn’t used by every function. I tried doing this by appending <?php echo get_the_ID();?> to my function name, which results in myFunction123, but the console reports “myFunction is undefined”.

    Any ideas?

    <button onclick="tester()">Tester</button> <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?> <div id="invis-image<?php echo get_the_ID();?>"><?php echo $image[0];?> </div>
        <script> function tester<?php echo get_the_ID();?>() {
                var invisimg = document.getElementById("invis-image<?php echo get_the_ID();?>").innerHTML;
                document.getElementById("player-img").src = invisimg;
                
            }
        
        </script>
Viewing 4 replies - 1 through 4 (of 4 total)
  • Thread Starter unsavouryindividual

    (@unsavouryindividual)

    Excuse my noobish mistake. I forgot to change my onclick variable, but my function no longer wants to play ball.

    Moderator bcworkz

    (@bcworkz)

    Instead of defining a complete function for each element, why not have just one function which is passed the clicked element’s ID. Sort of pseudo-code, as it would appear in HTML where PHP had already executed and output content:

    <button onclick="tester( 123 );">
    <script>
    function tester( theID ) {
      var source = element.getImageSource( theID );
      otherElement.src = source;
    }
    </script>

    Fake object references and methods for clarity in illustration of the passing the ID concept. 123 is the only thing PHP echoes out. The button element would be in the loop, but the script block only occurs once outside the loop.

    I think it’s more performative to alter element class attributes instead of its src attribute. You could have all the images in place consecutively, but they are all but one hidden with CSS using a specific class attribute, let’s say “hidden”.
    .hidden { display: none; }
    On click, script would add the “hidden” class to the currently displayed image and remove it for the image that should be displayed.

    Back to the passing the ID concept. jQuery does this automatically. You use CSS style selectors to define elements where we should listen for a click event. When the event callback executes, the clicked on element is available as this within the function. You may decide it’s not worth invoking jQuery on this page, but FYI the ability to add listeners by CSS selectors and access the related element with this is where jQuery can really be an advantage. IMHO of course 🙂

    Thread Starter unsavouryindividual

    (@unsavouryindividual)

    Thank you @bcworkz ! This didn’t occur to me.
    My reasoning behind me choosing to not simply switch the display attributes (good idea, by the way) is because I’m targeting an <audio> tag also and want to avoid having an invisible audio file playing on top of the currently selected one.
    I could also just learn how to pause the hidden element with JQuery, come to think of it lol

    Thread Starter unsavouryindividual

    (@unsavouryindividual)

    Thanks to bcworkz I have solved my puzzle. Here’s my work for anybody who might happen along here in the future.

    Inside the loop:

    <button style="background:#289700;" onclick="playEpisodes(<?php echo get_the_ID();?>)">Play Episode</button>
    
        <div style="display:none" id="invis-image<?php echo get_the_ID();?>"><?php echo $image[0];?></div>
        <div style="display:none" id="invis-mp3<?php echo get_the_ID();?>"><?php echo the_field('link'); ?></div>
        <div style="display:none" id="invis-url<?php echo get_the_ID();?>"><?php echo the_permalink(); ?></div>

    Outside loop:

    <script> function playEpisodes(theID) {
            
            // Make player visible
                document.getElementById("player").style.display = "inherit";
            
            // Calculate Source IDs
                var imageElement = "invis-image" + theID;
                var mp3Element = "invis-mp3" + theID;
                var urlElement = "invis-url" + theID;
            
            // Insert the image
                var invisimg = document.getElementById(imageElement).innerHTML;
                document.getElementById("player-img").src = invisimg;
            
            // Insert URL
                var invisurl = document.getElementById(urlElement).innerHTML;
                document.getElementById("ep-url").action = invisurl;
            
            // Insert the mp3
                var invismp3 = document.getElementById(mp3Element).innerHTML;
                            
            // Play the mp3
            document.getElementById("audio-source").src = invismp3;
            document.getElementById("download").href = invismp3;
                var audio = document.getElementById('audio-source');
    audio.play();
            document.getElementById("ply").style.display = "none";
            document.getElementById("pse").style.display = "inline-block";
                }
        
        </script>

    And my player:

    <div style="display:none" id="player" class="pcast-player">
          
        <img id="player-img" style="width: 100px;float: left;padding: 10px;" src="">
    <div class="pcast-player-controls">
        <button id="ply" title="Play" class="pcast-play"><i class="fa fa-play"></i></button>
        <button id="pse" title="Pause" class="pcast-pause"><i class="fa fa-pause"></i></button>
        <button title="Remind" class="pcast-rewind"><i class="fa fa-fast-backward"></i></button>
        <button title="Forward" class="pcast-forward"><i class="fa fa-fast-forward"></i></button>
        <span class="pcast-currenttime pcast-time">00:00</span>
        <progress class="pcast-progress" value="0"></progress>
        <span class="pcast-duration pcast-time">00:00</span>
        <button title="Change Speed" class="pcast-speed">1x</button>
        <button title="Mute" class="pcast-mute"><i class="fa fa-volume-up"></i></button>
        <button title="Download" class="pcast-down"><a id="download" style="color:#fff" href="" class="fa fa-download" download=""></a></button>
        <form style="display:inline-block;" id="ep-url" method="get" action=""><button type="submit" title="Visit episode page">Episode details</button></form>
      <audio id="audio-source" src=""></audio>
    
    </div>

    The functionality is that the button is clicked within an item in the loop, the fixed position player appears (display:none to display:inherit) with the post’s data loaded into it, it plays automatically, and can be replaced by clicking a button in another item – starting the process over again.

    Thanks to the whole WordPress community!

Viewing 4 replies - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.