Switching out one block of HTML with another in JavaScript is a powerful way to dynamically update

I am working on creating a feature on a webpage where clicking a button will change the HTML code inside a specific div. Essentially, I want to be able to update the content of a div by simply clicking a link.

Here are two different sets of HTML code:

Code Example One (id = contentPOP)

<div id="contentPOP">
            <h3>Hit like a girl entry, "Little Black Dress" by One Direction</h3>
            <iframe width="500" height="300"    
                    src="https://www.youtube.com/embed/QW6naMc6TWk?list=UUHe-Lb7DWhwT5S7Vzn7abxA"
                    frameborder="0" allowfullscreen>   </iframe>
                <br>
            <h3>Remembering Steve Jobs</h3>
             <iframe width="500" height="300"
                     src="https://www.youtube.com/embed/q7oyy0FjhAY?list=UUHe-Lb7DWhwT5S7Vzn7abxA"    
                     frameborder="0" allowfullscreen></iframe>
        </div>

Code Example Two (id = "contentNEW")

<div id="contentNEW">
          <h3>Slow Motion War!</h3>
            <iframe width="500" height="300" 
                    src="https://www.youtube.com/embed/Y2996S-8oEU?list=UUHe-Lb7DWhwT5S7Vzn7abxA" 
                    frameborder="0" allowfullscreen></iframe>
            <br>
            <h3>1 Year Anniversary of Teddy Bear Productions!</h3>
            <iframe width="500" height="300" 
                    src="https://www.youtube.com/embed/7Tim_K74ua8?list=UUHe-Lb7DWhwT5S7Vzn7abxA" 
                    frameborder="0" allowfullscreen></iframe>
        </div>

View an example of the code here

Please provide a detailed explanation as I am unfamiliar with how to achieve this. Additionally, I would prefer to accomplish this using only JavaScript, without the use of jQuery.

Answer №1

To start, you need to uncomment the following code snippet so it appears on the page:

<!--THE BELOW CODE SHOULD REPLACE THE ABOVE CODE
<div id="contentNEW">
  ...
</div>
-->

Then, use CSS to hide it:

#contentNEW { display: none; }

Next, incorporate the following code into your newVids() function:

function newVids() {
  // identify the target div for modification
  var div = document.getElementById('contentPOP');
  // update its content with the hidden div's content
  div.innerHTML = document.getElementById('contentNEW').innerHTML;
}

This approach may not be the most efficient way to accomplish your goal. Instead of toggling visibility, consider swapping one div out for another.

Answer №2

If you want to easily toggle between two chunks of code, simply wrap each one in its own div with unique IDs and use jQuery to target them. One of the divs should initially have a "display:hidden" class, which can be toggled on and off with ease.

For an example, check out THIS LINK!!!

Wishing you good luck as you implement this solution!

HTML

<p>This is a paragraph.</p>
<p id="hidden-paragraph" class="hidden">This is a second paragraph.</p>
<button>Toggle </button>

CSS

.hidden{
   display:none;
}

JS

$(document).ready(function(){
   $("button").click(function(){
       $("#hidden-paragraph").toggle();
   });
});

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

Top tip for combating form misuse in Django applications

Is there a reliable method to restrict form submissions in Django? I need the form to be submitted a maximum of 5 times from the same IP address within one hour. Can this restriction be implemented in Django? I experimented with Django Ratelimit, but unfo ...

Is there a way to transfer gulp.watch() to a pipe?

Currently, I have a basic task set up for linting changed JavaScript files: gulp.task('default', function() { // monitor JS file changes gulp.watch(base + 'javascripts/**/*.js', function() { gulp.run(&ap ...

Triggering an event from a component to its parent module resulting in an exception situation

Here is my app.component.ts code: import { Component, Input, OnInit, OnChanges, SimpleChanges} from '@angular/core'; import {Counter } from './counter' @Component({ selector: 'my-app', template: ` <custom-counter [ ...

"Receiving a 404 error when sending a POST request, but getting

When attempting to send a POST request, I encountered a 404 error response from the server. Strangely, when sending a GET request, I received a 200 response. I have experimented with different methods: $.ajax({ type:"POST", url: "script.php", ...

Attempting to populate HTML content retrieved from my MySQL database

Currently, I am attempting to retrieve HTML content stored in my MySQL database using nodejs. The products are being retrieved from the database successfully. export async function getAllProducts() { try { const response = await fetch('ht ...

Downloading multiple files on both iOS and Android devices

Is there a way to download assets (mp3/jpeg) in an Asynchronous manner? I have over 200 files in each case and the process is taking too long. Are there any techniques to speed up the download process on both iOS and Android? ...

Tips for resolving the error "Parsing near 'Unexpected end of JSON input while parsing...' for...'mocha':'^3.2.0','s'":

Once I've successfully set up react and react-dom, the next step is to install webpack. However, I encountered an error during this process. To troubleshoot, I decided to install babel-loader first to ensure that both npm and my internet connection a ...

Adjust background image size to fit the screen, not just the content

Whenever I set the background image for each page using the following JavaScript code, var imageUrl = 'url(' + imageUrl + ') top left no-repeat fixed'; $('body').css({ 'background': imageUrl }); I also add ...

Sending documents to a printer directly from a Rails application

Is there a library or gem in Rails that can be used to print the contents of a web page directly onto paper? I am curious if it's possible to specify only a specific part of the page, such as a div, for printing. Any guidance, advice, or tutorial link ...

FadeOut/FadeIn Iframe Animation

Help needed with making an iframe fade in and out using jQuery. Something seems off with the code and I can't figure out why it's not working. Can anyone spot the mistake? HTML <body> <center> <div class="headbackground" ...

Enhancing the appearance of each letter within a word

I am currently working on styling the word "Siteripe". Each letter should have a different color, just like it is shown on this website. I have successfully styled only the first letter using the following CSS code: #namer:first-letter { color:#09C; f ...

Set iframe or form to be in a fixed position

Having issues with my site where an iframe is contained within a div. When only one character is entered in the telephone box, validation fails and red warning text is displayed. Furthermore, after clicking in the email box and pressing tab twice, the fo ...

Tips for aligning thumbnail text to the right on a small viewport with Bootstrap

Here is a visual representation of the standard thumbnail layout Once the viewport reaches the small size, the layout should switch to this design: Bootstrap only shrinks the container by default, as demonstrated in this jsfiddle: http://jsfiddle.net/32 ...

Rotate a div using CSS by 10 degrees while spanning the full width

I stumbled upon the website recently, particularly noticing the Social News section on the side. I am curious about how to create rotated divs (around 10 degrees) that span the full width of a webpage. Is it possible to make this responsive so that it wor ...

Create a list of items with checkboxes next to each that can be repeated using PdfMake

Incorporating pdfMake into my project, I am trying to display text next to an image and replicate this section in my docDefinition. The issue arises when I attempt to repeat this part using the following code snippet: { columns: [ { ...

How to loop through a list variable using Razor syntax in an HTML document

Exploring the world of asp .net and MVC is a new adventure for me. I have delved into a service method named Jumbo(), which delivers a list consisting of first names, last names, and contact numbers. In my main project, I invoke this method in the followin ...

Switch color in Material-UI based on props

Utilizing code inspired by the Material-UI documentation on customizing the switch, you can customize the switch color to be blue: import React from 'react' import Switch from '@material-ui/core/Switch' import {withStyles} from '@ ...

How can you stop VueUse useStorage from filling localStorage again after clearing it?

Using Vue 3 in combination with VueUse's useStorage to sync reactive state with localStorage has presented a challenge for me. Whenever I programmatically clear localStorage during user logout processes, it seems to automatically refill with previous ...

Every time I launch my express application, I encounter this error message

Encountering a type error with Express Router middleware. See below for the code snippets and error details. Any assistance is appreciated? The application is functioning properly, but when attempting to access the URL in the browser, the following error ...

Access a file from a specified route within Express

Recently, I created a custom Node module that requires a configuration file in CSV format. My goal is to implement this module within an Express Route module; however, I am encountering difficulties related to the loading of the configuration file. Should ...