arjwolf arjwolf - 3 months ago 12
Javascript Question

JavaScript Function Switch Function Not Working

I recently posted a question and suggested this as an answer but it is not working. Why ?

<div class="text-center">
<embed src="https://www.setasign.com/files/demo-files/pdfs/lenstown/Fact-Sheet.pdf" width="300" height="300" type='application/pdf' id="thePdf">
</div>

<div class="button">
<button class="btn-info" type="button" onclick="switchPdf();">Search</button>
</div>

<script>
function switchPdf() {
var fileA = 'https://www.setasign.com/files/demo-files/pdfs/lenstown/Fact-Sheet.pdf',
fileB = 'https://www.setasign.com/files/demo-files/pdfs/tektown/Fact-Sheet.pdf',
elem = document.getElementById('thePdf');

elem.src = elem.src == fileA ? fileB : fileA;
}
</script>


Basically there is a default PDF which loads on page open, and once I click the button I want the pdf to change to the other pdf. But it is not working

Answer

changes to src attribute on <embed>, <object>, etc...
do not take affect

have to replace with a new element

function switchPdf() {
    var fileA = 'https://www.setasign.com/files/demo-files/pdfs/lenstown/Fact-Sheet.pdf',
        fileB = 'https://www.setasign.com/files/demo-files/pdfs/tektown/Fact-Sheet.pdf',
        container = document.getElementById('thePdfContainer'),
        elem = document.getElementById('thePdf');

    var newFile = (elem.src === fileA) ? fileB : fileA;
  
    container.innerHTML = '<embed src="' + newFile + '" width="300" height="300" type="application/pdf" id="thePdf">';

    console.log(container.innerHTML);
}
<div id="thePdfContainer" class="text-center">           
    <embed src="https://www.setasign.com/files/demo-files/pdfs/lenstown/Fact-Sheet.pdf" width="300" height="300" type='application/pdf' id="thePdf">
</div>

<div class="button">
    <button class="btn-info" type="button" onclick="switchPdf();">Search</button>
</div>