I have a problem. I used javascript for settings display block or display none. I get an error in the console “Uncaught TypeError: Cannot set property ‘onclick’ of null at script.js?ver=1.0.0:15”. I added a script tag in the header, then in the footer and still the same. Also I added defer in my script tag and still nothing. Function it works on another site.
JS Code
JavaScript
x
12
12
1
var element = document.getElementById('powierzchnia');
2
if (element.className === 'show col-12 gallery-block grid-gallery') {
3
element.className = 'hide col-12 gallery-block grid-gallery';
4
document.getElementById('powierzchnia_chup').style.display = 'none';
5
document.getElementById('powierzchnia_chdown').style.display = 'inline';
6
} else {
7
element.className = 'show col-12 gallery-block grid-gallery';
8
document.getElementById('powierzchnia_chup').style.display = 'inline';
9
document.getElementById('powierzchnia_chdown').style.display = 'none';
10
}
11
}
12
HTML and PHP code
JavaScript
1
26
26
1
<div class="first-box">
2
<h4 id="show-powierzchnia" style="cursor: pointer;">
3
<span>Powierzchnia panela</span>
4
<span class="span-fr">
5
<img id="powierzchnia_chup" style="display: none;" src="<?php echo get_template_directory_uri(); ?>/img/chervon-up.svg" />
6
<img id="powierzchnia_chdown" src="<?php echo get_template_directory_uri(); ?>/img/chervon-down.svg" />
7
</span>
8
</h4>
9
</div>
10
<div id="powierzchnia" class="hide col-12 gallery-block grid-gallery">
11
<div class="row">
12
<?php
13
foreach( $media_wzory_powierzchnia as $wzory ){
14
echo '<div class="col-md-3 item item-custom-gallery mb-3">';
15
echo '<a class="lightbox" href="'.wp_get_attachment_url($wzory['zdjecie_powierzchni']).'">';
16
echo '<img class="img-gallery image scale-on-hover" src="'.wp_get_attachment_url($wzory['zdjecie_powierzchni']).'">';
17
echo '<div class="w-100 text-center">';
18
echo '<h5>'.$wzory['nazwa_powierzchni'].'</h5>';
19
echo '</div>';
20
echo '</a>';
21
echo '</div>';
22
}
23
?>
24
</div>
25
</div>
26
Advertisement
Answer
try using DOMContentLoaded event:
JavaScript
1
14
14
1
document.addEventListener("DOMContentLoaded", function() {
2
// code...
3
var element = document.getElementById('powierzchnia');
4
if (element.className === 'show col-12 gallery-block grid-gallery') {
5
element.className = 'hide col-12 gallery-block grid-gallery';
6
document.getElementById('powierzchnia_chup').style.display = 'none';
7
document.getElementById('powierzchnia_chdown').style.display = 'inline';
8
} else {
9
element.className = 'show col-12 gallery-block grid-gallery';
10
document.getElementById('powierzchnia_chup').style.display = 'inline';
11
document.getElementById('powierzchnia_chdown').style.display = 'none';
12
}
13
});
14
Now the script should run only when the Html content has been loaded 🙂