How can PHP be integrated with JavaScript to achieve dynamic image rotation on a webpage?
To achieve dynamic image rotation on a webpage, PHP can be used to generate JavaScript code that handles the rotation of images. This can be done by dynamically updating the image source attribute in the JavaScript code. By integrating PHP with JavaScript in this way, you can create a dynamic and interactive image rotation feature on your webpage.
<?php
$images = array('image1.jpg', 'image2.jpg', 'image3.jpg');
?>
<script>
var images = <?php echo json_encode($images); ?>;
var currentIndex = 0;
function rotateImage() {
currentIndex = (currentIndex + 1) % images.length;
document.getElementById('rotating-image').src = images[currentIndex];
}
setInterval(rotateImage, 3000); // Rotate image every 3 seconds
</script>
Related Questions
- What are the potential benefits of using the alternative syntax for control structures in PHP templates?
- What are some potential pitfalls when using SQL queries in PHP to search for specific data in a database?
- What are the advantages and disadvantages of using preg_match versus other string comparison functions in PHP?