Search code examples
javascriptpdfgetelementbyidselectors-api

getelementbyid more parameters


I'm working on a project and I need to show/hide several pdfs on html page. This is the part at which the pdf is shown (on click show and hide other pdf)

It acts fine with 2 pdfs. But I need to hide more than one pdf at the time. For example:

on click: Laplace.pdf shows up, while Fourier.pdf AND Z.pdf AND integral.pdf must hide of. And so on...

I see the thing is at the <<var hide = document.getElementById('test');>> but i can't make getelementbyID work for more IDs. I tried to make it with document.querySelectorAll, but it doesn't work.

Here is a portion of my HTML:

<input type="button" onclick="var id = document.getElementById('test'); var hide = document.getElementById('test2'); if(id.style.display == 'block'){ id.style.display = 'none'; id.style.visibility = 'hidden'; }else{ id.style.display = 'block'; id.style.visibility = 'visible';  hide.style.display = 'none'; hide.style.visibility = 'hidden';}" value="preview pdf" class="button"/>

<embed src="laplace.pdf" style="WIDTH:60%; HEIGHT:500; display:none;  visibility: hidden;" id="test" name="test"> 

Any help would be really thankful.


Solution

  • I have changed the whole answer to be using jQuery. You have to:

    1. Add a class pdf on all the embed element of the pdfs (class="pdf").
    2. Add a data attribute on the buttons to contain the equivalent ID (data-pdf="test" ...). And remove the onclick property it won't be needed.
    3. And of course add the CSS for the class hidden.

    $(function() {
      $("embed.pdf").addClass("hidden");       // on load, hide all pdfs
    
      $("[data-pdf]").click(function() {       // when clicking an element with the attribute data-pdf (the buttons)
        var id = $(this).data("pdf");          // get the value of that data-pdf attribute (which is the id of the pdf element to show or hide)
        $this = $('#' + id);                   // get the pdf element itself using that id
        if ($this.hasClass("hidden")) {        // if the element is hidden
          $("embed.pdf").addClass("hidden");   // then hide all other pdfs
          $this.removeClass("hidden");         // and show it
        } else {                               // otherwise
          $this.addClass("hidden");            // hide it
        }
      });
    });
    .hidden {
      display: none;
    }
    
    embed {
      border: 1px solid black;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="button" data-pdf="test" value="show test" />
    <input type="button" data-pdf="other" value="show other" />
    <input type="button" data-pdf="something" value="show something" />
    
    <embed src="test.pdf" id="test" name="test" class="pdf">
    <embed src="pdf.pdf" id="other" name="other" class="pdf">
    <embed src="yet another.pdf" id="something" name="something" class="pdf">