"Discover the proper method of referencing an iframe element from an HTML file using JavaScript

I am currently exploring the world of html and CSS, but now I am interested in delving into JavaScript, a topic I am completely unfamiliar with!

My goal is to create a random button that displays a randomly selected embedded video (for example, from a pool of 1-5 videos) within an iframe. After some research on Google, I came across a JavaScript/(jQuery?) code snippet:

<script type="text/javascript" src="jquery-1.11.0.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {

var array=["Item1", "Item2", "Item3", "Item4", "Item5"];
$('#button').bind('click', function() {

    var random = array[Math.floor(Math.random() * array.length)];
    $("h1").html(random);
});
});
</script>

Accompanied by the following html code:

<h1>Will be replaced</h1>
<button id="button">Random</button>

Imagine having the following iframe embedded in my html:

<iframe width="640" height="360" src="http://www.youtube.com/embed/npvNPORFXpc"     frameborder="0" allowfullscreen></iframe>           

My intention is to have this embedded video displayed on the page, and upon clicking the random button, it should switch to another one from the 1-5 video options. How can I incorporate this as an item in the JavaScript, ensuring each number corresponds to a unique video?

Another issue I encountered:

There are instances where the same number is generated, causing the same video to appear again. Any guidance on how to tackle this would be greatly appreciated!

Answer №1

Although it may not seem like much, it's a solid starting point: Check it out here

Just snagged the first 5 video IDs I could find :))

Take a look at the JavaScript code below:

$(document).ready(function() {
    var array=["FOIjvHjK0Rw", "CcsUYu0PVxY", "dE_XVl7fwBQ", "iIwxR6kjTfA", "USe6s2kfuWk"];
    $('#button').bind('click', function() {
        var random = array[Math.floor(Math.random() * array.length)];
        $("h1").html(random);
        var url="http://www.youtube.com/embed/"+random;
        $('#frame').attr('src', url);
        $('#frame').css('visibility','visible');
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The MaterialTable is unable to display any data

After calling the fetch function in the useEffect, my getUsers function does not populate the data variable. I am unable to see rows of data in the MaterialTable as the data structure is in columns. I need help figuring out what I'm doing wrong. func ...

Tips for managing large amounts of data retrieval from an API

As a beginner, I am attempting to retrieve data from an API and display it using the v-for directive. However, this process is causing my app to lag. It freezes when new data is fetched or when I search within the list. The following code snippet shows whe ...

Extract information from an HTML table into PHP

I have an HTML table that is generated dynamically and I am looking to extract the data from it using the POST method. Is there a way to accomplish this? Are there any alternative methods you would suggest for achieving this goal? Below is a basic example ...

I require a modification in the style of every anchor element found within a div containing the designated class

In a div with the class fview, there is a nested element called iNside which contains a span. Additionally, there are anchor elements within another span, ul li, and another div, among others. I want all anchor elements to have the same style. I tried app ...

Looking to trigger the closing of a q-popup-proxy by clicking a button from a separate component

I am currently working with a q-popup-proxy component in my project. <q-btn label="Add Fault" class="addFaultButton" dense @click="openPopUp()"> <q-popup-proxy position="center" v-if="openFaults" ...

`Vue JS table with Boostrap styling showcasing a loading indicator for busy state`

Issue: I need to show a loading icon while waiting for the table to load. https://i.sstatic.net/kRCbL.png I am utilizing Boostrap-vue JS, which is built on top of Bootstrap, and VueJS's "b-table" component to display approximately 3000 rows in a tabl ...

What is the best way to ensure a PrimeVue TabPanel takes up the full vertical space and allows the content within the tabs to be scroll

I have created a sandbox demo to illustrate my issue. My goal is to make the content of tabs scroll when necessary but fill to the bottom if not needed. I believe using flex columns could be the solution, however, my attempts so far have been unsuccessful. ...

How can we retrieve a jQuery selector from a $.get() function

When utilizing $.get() to fetch data, it successfully retrieves the entire HTML page. I am looking for a way to use selectors on the fetched data in order to extract specific information from elements, similar to how I would use $('.someclass') ...

What is the best way to overlay a video onto an image using HTML and CSS?

Currently, I am experimenting with a layering technique in HTML/CSS. The idea is to place an image behind a video to enhance the overall look of the video section. Here is a sample photoshop mockup that demonstrates what I am aiming for: HTML div id= " ...

"Customize your jQuery Ajax request to ensure a clean cache by refreshing data

Seeking a solution for no-cached ajax requests due to issues with cached responses. Modifying the original code from a plugin is not an option, so I require a stable solution to address this problem. I attempted the following code: jQuery.ajaxSetup({ c ...

Laravel and jQuery: A Perfect Match for Routing

Using Ajax to fetch and display content in a Laravel view, I am trying to figure out how to access the second parameter from the URL. Currently, it is returning a random string: for(var i=0;i<array.length;i++){ html+="<a href={{ route('show ...

The functionality of Three.js arc drawing in canvas renderer seems to have encountered issues on Chrome

Looking at this example from the library, it is clear that the circles are adjusting their line width and appear thin when they are in close proximity. This functionality used to function properly. Currently, I am using Chrome version 27.0.1453.93 on OSX ...

What is the best way to ensure that each service call to my controller is completed before proceeding to the next one within a loop in Angular?

Calling an Angular service can be done like this: this.webService.add(id) .subscribe(result => { // perform required actions }, error => { // handle errors }); // Service Definition add(id: number): Observable < any > { retu ...

Guide on Declaring an Array in a Node Module and Another JavaScript File (Mongodb)

As a beginner in node.js and programming, I am on a journey to understand how to retrieve a variable's value from Mongodb. Within my app.js file, I have the 'data' variable set up. var data = require("./public/assets/js/data.js"); app.get(& ...

Create a serverless PowerShell script on Azure that generates HTML content to display on a web browser

Recently, I developed a PowerShell script in Azure serverless that generates HTML content. It works perfectly fine when accessed from Firefox or Chrome as the HTML document opens in the browser. However, the issue arises when using Microsoft's browser ...

Extracting information from a table containing both obscured and accessible rows

Currently, I am attempting to scrape data from this specific website by utilizing Selenium. While my code successfully loads the desired table, I encounter challenges when trying to extract data from hidden rows, even though the information is visibly pres ...

Utilizing a particular Google font site-wide in a Next.js project, restricted to only the default route

My goal is to implement the 'Roboto' font globally in my Next.js project. Below is my main layout file where I attempted to do so following the documentation provided. import type { Metadata } from "next"; import { Roboto } from "n ...

If there are no spaces, text will be removed from my list group

While working on developing a forum, I encountered an issue where if I repeatedly input letters or words without any spaces, it causes everything to overlap. Below is an example highlighting this problem: https://i.sstatic.net/KStNq.png Although there is ...

What is the best way to filter out empty arrays when executing a multiple get request in MongoDB containing a mix of strings and numbers?

I am currently working on a solution that involves the following code: export const ProductsByFilter = async (req, res) => { const {a, b, c} = req.query let query = {} if (a) { query.a = a; } if (b) { query.b = b; } if (c) { ...

Encountering difficulties in loading my personal components within angular2 framework

I encountered an issue while trying to load the component located at 'app/shared/lookup/lookup.component.ts' from 'app/associate/abc.component.ts' Folder Structure https://i.stack.imgur.com/sZwvK.jpg Error Message https://i.stack.img ...