Click event triggers the loading of a page

Recently, I found a simple jQuery event that loads a page into an iframe within the corresponding div when clicked.
You can check out the JS Fiddle example here

Now, my goal is to achieve the following:

  1. Instead of using separate codes for #frame1 and #frame2, I want to load events using the same code.

    showIframe = function (url) {
    document.getElementById('iframetarget').src = url;
    document.getElementById('frame').style.display = 'block';
    }

  2. When clicking on 1 in the list style, the corresponding iframe page should load. Similarly, clicking on 2 should load the respective iframe page while hiding or "killing" the page loaded for 1

You can view the desired fiddle demo here

I've tried using the document.getElementByClassName syntax since using the same ID in different divs is not possible, but it doesn't seem to work. Any help would be greatly appreciated.

Answer №1

Check out this helpful jsFiddle example. Both iframes in the code snippet below are linked to the buttons via data-url value.

var buttons = document.getElementsByClassName('iframe-btn');
for( var x=0;x<buttons.length;x++){
    buttons[x].addEventListener("click", function(event){
        event.preventDefault();
        var urlValue = this.getAttribute('data-url');
        var targetFrame = this.getAttribute('href').split('#')[1];

        var iframeElements = document.getElementsByTagName('iframe');
        for( var y=0;y<buttons.length;y++){
            iframeElements[y].src='';
        }
        document.getElementById(targetFrame).src = urlValue;
        document.getElementById(targetFrame).style.display = 'block'; 
    }, false);
}

Answer №2

Hopefully this code snippet works as expected! I am utilizing the getelementbyClassName attribute in this example.

http://jsfiddle.net/uniqueusername/abcdefg123/

Below is the HTML code:

<ul>
<li><a href="#frame" onclick="showIframe('http://www.website.com/');">1</a></li>
<li><a href="#frame" onclick="showIframe('http://example.com/');">&nbsp;2</a></li>
</ul>  

<div id="frame" style="background-color:#9C27B0">
<iframe id='iframetarget' class="full" frameborder="0" src=""></iframe>
</div>

Javascript function:

showIframe = function (url) {

    var divs = document.getElementsByClassName('full');
for(var i=0; i < divs.length; i++) { 
  divs[i].src = url;
}

    //document.getElementByClassName('full').src = url;
    document.getElementById('frame').style.display = 'block';
}

CSS styles:

ul{list-style:none;position:fixed;margin:0;padding:0;}
ul li{float:left}
a{text-decoration:none}

.full {width:100%; height:100%;}

Answer №3

Implementing jquery functionality with the following code

HTML

<ul>
<li><a href="#frame1" onclick="showIframe('http://www.uibrush.com/');">1</a></li>
<li><a href="#frame2" onclick="showIframe2('http://imgur.com/');">&nbsp;2</a></li>
</ul>
<br><br>


<div id="frame1" style="background-color:#9C27B0">
<iframe id='iframetarget1' class="full" frameborder="0" src=""></iframe>
</div>
<br>


<div id="frame2" style="background-color:#ffd800">
<iframe id='iframetarget2' class="full" frameborder="0" src=""></iframe>
</div>   

Javascript

$("#link1").click(showIframe);
$("#link2").click(showIframe);

function showIframe() {
   var target ='#'+ $(this).attr('data-target');
   var url = $(this).attr('data-url');
   $(target).attr('src',url);  
   $(target).parent().css("display:'block'");
}

Link to Working Example

Answer №4

  1. To add event listeners programmatically, you can use code like this:

    $('#element').on('click', function(){ //logic });

  2. Each event carries an object to the handler, which contains the executor. You can assign data-* attributes to the executor, such as holding a URL or other information.

Here are some useful references:

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

How can I retrieve a Jquery tooltip from a HiddenField?

I am trying to utilize a hidden field in my asp.net calendar to display a message using JQ Tooltip. However, when I attempt to use the value of the HiddenField for the tooltip, I encounter an error. $("#hf_taskID_cal").tooltip($("#hf_taskID_cal").val()); ...

How to create vertical spacing between <a> elements within the same div using HTML and CSS

Currently, the layout in picture 1 shows how my content is displayed. I am looking to create spacing (bottom margin?) between the images like the example in picture 2. The two side-by-side blocks are separate DIVs, and the images within each line belong to ...

What impact does utilizing CSS 3D Transforms have on search engine optimization (SEO)?

Google emphasizes the importance of not hiding content, as it may not be counted by search engines. However, Google Cache has shown some discrepancies in understanding certain elements correctly. It's possible that what Google perceives as hidden migh ...

The input range in ChromeVox is behaving incorrectly by skipping to the maximum value instead of following the correct step value

Attempting to get an input type="range" element to function correctly with ChromeVox has presented me with a challenge. Here's what I'm facing: When I press the right arrow key to move forward, it instantly jumps to the maximum value of 100 in ...

What is the best way to display an image and text side by side within a single row in react-table?

I am trying to display an image and text side by side within a single column in a React table. I have successfully added two texts together in a single column using the code below: Header: "Name", id: "User", accessor: (d) => ...

Gather data from a variety of HTML5 video seminars

I am encountering an issue where I have multiple videos and I want to receive events from each of them. However, I am only able to get the event from one video (as tested in Chrome). Why is this happening? Here is the HTML code: <video id="video1" pre ...

Minimize CPU consumption in your threejs application

I've been working on a project where I'm coding Snake in Threejs (I know there are simpler methods). Everything works smoothly until the snake reaches a certain size, causing CPU usage to spike to 50% or more and freezing the entire browser tab. ...

Set up bootstrap 5 on your website while incorporating the beloved color scheme of bootstrap

Bootstrap has introduced new color schemes in version 5 compared to version 4. Is it possible to update to Bootstrap 5 while retaining the original color palette of Bootstrap 4 without the need for manual file adjustments? Are there any content delivery ...

Blending HTML elements with ASP.NET code

Trying to concatenate two strings separated by a line break. This snippet shows what I am attempting: <td>@(string.Join("<br /> ", report.TimeReportProjects.Select(x => x.Project.ProjectName)))</td> <td>@(string.Join("<br /& ...

Bootstrap Popover not displaying information after an AJAX request

I'm struggling to update the popovers contents with Ajax result in my ASP.Net MVC4 project. Using ASP.Net (MVC4): public ActionResult GetEmployeeDetails(string employeeId) { var contract = UnitOfWork.ContractRepository.ContractBu ...

Creating visualizations by overlaying shapes onto images using specified coordinates in jQuery

I have a web application in development that integrates with the skybiometry API. Their demo showcases a fantastic user feedback system displayed after facial recognition, similar to the one shown below. I am currently working on implementing a similar fe ...

When using jQuery and Laravel, why does the element not appear when setting its display to block after receiving a response?

Trying to handle data (id) retrieved from the database and stored in a button, which appears in a modal like this: There are buttons for "Add" and "Remove", but the "Remove" button is hidden. What I want to achieve: When the user clicks on the "Add" but ...

The CSS styles for a:link, a:active, and a:visited do not seem to work with

My page contains the following CSS rule: a:link,a:active,a:visited{text-decoration:none;} I have encountered an issue where this rule is not working as expected. To apply the rule within a div with the id="test", I had to modify the rule like this: #tes ...

Could one potentially include the if statement within `${'put your code here'}`?

Is there a way to incorporate the if condition within ${ } using jQuery? $('#inactive_list_body').append(` <tr> <td>${value['name']}</td> <td>${ if(value['status'] == 'false'){ ...

Error in jQuery Audio Player - Promise rejection (DOMException): Unable to load due to absence of compatible source

As part of a language learning platform, I decided to create my own audio player. Each page on the site features multiple player buttons designed to play specific examples' corresponding sounds. However, I've noticed that occasionally some of th ...

What might be causing issues with the functionality of my user registration form?

I have been working on creating a registration form for users using PHP and MySQL. However, I'm facing an issue where no new records are added to the database when I submit the form. It's strange because the database has worked perfectly fine wit ...

What is the reason behind observing numerous post requests in the Firebug console after submitting a form through Ajax in jQuery?

I have integrated the jquery Form plugin for form submission and everything seems to be functioning properly. However, upon turning on the firebug console and clicking the submit button, I notice that there are 10 post requests being sent with the same da ...

Challenge encountered in handling AJAX response data for presentation

Currently, I am immersed in a project and decided to implement AJAX for smoother form submissions. My initial attempt was trying to display text from a .txt file below the "submit" button, but unfortunately, that approach didn't yield the desired resu ...

Building a versatile and interactive table using AngularJS with data sourced from a

I am currently working on creating a dynamic table using Angular JS to display data received from a Spring Rest Service. Here is the code snippet I have been working with: // JavaScript Document var app = angular.module("SDLC", []); app.config([&apos ...

"Enhance your website with dynamic drop-down menus using

Currently, I am working on creating a dynamic menu using Twitter Bootstrap by loading JSON files that contain the menu items. The structure of the JSON file looks like this: // test.json { "children": [ { "text": "Item1", "children": [ ...