I have been working on a slick slider, now I want to have custom arrows and for doing that I am using the default method from slick which is having prevArrow: and nextArrow: and those buttons(which work) areinside the slick slider, but I dont want that so I added another prev and next buttons outside the slick-slider container and to give these buttons the functionality of the default ones Im using javascript. While in the process there is an error with the javascript part which returns this error "Cannot read property ‘click’ of null at HTMLButtonElement". How can this error be fixed?
html
<div class="mates">
<button class="prev-g" id="prev-gg">prev</button>
<button class="next-g" id="next-gg">next</button>
<div class="mates-container" id="mates-containerrr">
<button class="prev-h" id="prev-hh">prev</button>
<button class="next-h" id="next-hh">next</button>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('.mates-container').slick({
infinite: true,
speed: 450,
slidesToShow: 1,
slidesToScroll: 1,
prevArrow: "<button class='prev-h' id='prev-hh'>prev</button>",
nextArrow: "<button class='next-h' id='next-hh'>next</button>",
});
});
</script>
<script type="text/javascript">
const badBtn = document.getElementById("next-hh");
const editedBtn = document.getElementById("next-gg");
editedBtn.addEventListener("click", function() {
badBtn.click();
});
</script>
If you need to see more code or have any questions please let me know in the comments please:)
3
Answers
You’re querying the document for the
badBtn
when the slick slider would not have loaded and possibly, would not have rendered its HTML into the page DOM. You should wrap your custom code afterslick
slider has been initialized.You should put your script inside
$(document).ready(function(){...})
. If you put outside ready function, the script will run without consideration of element whether is already rendered or not, that’s why it show you errorCannot read property 'click' of null at HTMLButtonElement
Hope this would help!
I would say you should use id ,not the class name $(‘.mates-container’)