Modify the class of a div element depending on the value of a data attribute

I am faced with a situation where I have an iframe and two different sets of CSS codes - one for landscape orientation and one for portrait orientation. However, these are not specifically for the device's orientation but rather for the content loaded within the iframe, such as games designed in either landscape or portrait mode.

Both sets of CSS work well individually when enabled, but I would like to have a single button that can trigger the loading of the iframe with the corresponding CSS based on a data attribute. For example:

<a href="mygamelink" target="iframe" data="portrait">click me to play</a>
    

Upon clicking the above link, the iframe should load/change its class accordingly to apply the portrait-specific CSS.

<a href="mygamelink" target="iframe" data="landscape">click me to play</a>
    

Similarly, clicking this link should load/change the iframe's class to apply the landscape-specific CSS.

<iframe class="portrait/landscape" name="iframe"></a>
    

I am aware that achieving this functionality is possible with jQuery. Any ideas on how to implement it?

Answer №1

Here is a functional code snippet.

Ensure that the links contain custom data attributes as shown below:

<a href="mygamelink" target="iframe" data-format="portrait" class="iframe_link">click me to play</a>
<a href="mygamelink" target="iframe" data-format="landscape" class="iframe_link">click me to play</a>

Add a click event listener to the links using a shared attribute (such as the class iframe_link) :

$('.iframe_link').on('click', function(e){
    e.preventDefault();

    $('[name="iframe"]').attr('class', ( $(this).data('format') ));
})

Answer №2

Weblinks

<a id="first-link" href="mygamelink" target="iframe" data-display="portrait">click here to begin</a>
<a id="second-link" href="mygamelink" target="iframe" data-display="landscape">click here to start</a>

Embedding Content

<iframe id="my-iframe" class="portrait/landscape" name="iframe"></a>

Applying CSS Class to iframe using jQuery:

var display = $("#first-link").data("display");
if(display === "portrait") {
    $("#my-iframe").addClass("portrait");
} else {
    $("#my-iframe").addClass("landscape");
}

Repeat process for other links or use a common class to group them together.

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

Is there a way to retrieve the ngModel reference of a child element within a directive's

I am currently utilizing bootstrap-colorpicker along with an angular directive in my project. Within my form, there is a colorpicker that I want to monitor for any changes. However, since the colorpicker jQuery plugin updates the value of the colorpicker, ...

Can you explain the distinctions between using this['key'] and $data['key'] in the context of v-model?

Take a look at the snippet below, which includes three demos. The first two demos are functioning correctly (v-model is working fine). However, in the last demo, when you type something into the <input>, you will notice that this['test 1'] ...

Emberjs Troubleshooting: Issue with Sending Many-To-Many JSON Parameters

My current versions are ember-cli 1.13.8 and ember-data 1.13.11, using ActiveModelAdapter. I am working with two objects: posts and users. On an individual post page, I have implemented an action that allows users to watch/follow the post. //post model j ...

Explore the inner workings and file contents of a package using the NPM registry API, by accessing a detailed JSON response

Can the NPM registry API be utilized to access an endpoint like https://registry.npmjs.org/jquery And examine the Tarbells structure and internal files without the need to download the package, in a JSON response similar to: { files: { js: registr ...

Creating an Active Link in Bootstrap 5.0 (Beta 3) Navbar Using JavaScript

I am currently working with Bootstrap 5 (Beta 3 - no JQuery) on a static website, and I am facing the challenge of making a navbar link appear active. I prefer to achieve this using JavaScript instead of creating a separate navbar for each page. For instan ...

Attempting to perform a cross-domain POST request in Internet Explorer 9

I've been attempting to execute a cross-domain POST request in IE9, and here's the code I'm using: $.support.cors = true; var data = {"userid":uid,"email":email,"password":password}; if (isIE () && isIE () <= 9) { $.ajax({ ...

Tips for showcasing a dataset within a table using Angular.js ng-repeat

I am encountering an issue where I have to present an array of data within a table using Angular.js. Below is an explanation of my code. Table: <table class="table table-bordered table-striped table-hover" id="dataTable" > <tbody> ...

Three.js: Buffer geometry does not provide any performance improvement

After examining the Three.js example found at webgl_performance, I decided to try improving performance by converting the model into a buffer geometry using the following code: var buffer = THREE.BufferGeometryUtils.fromGeometry( geometry ); Despite my e ...

Connect jQuery navigation button to a specific web address

Check out this cool jQuery menu script I found: <script type="text/javascript> jQuery(document).ready(function(){ jQuery('#promo').pieMenu({icon : [ { path : "/wp-content/t ...

The flexbox layout is not properly stacking div rows in a column

Objective: Creating a flexbox layout with a responsive background image that adjusts in height when the screen size changes, causing elements to wrap; In addition, there is a fixed header bar at the top of the page. The layout consists of a full-screen co ...

Selecting specific categories to display on the homepage and limiting the number of images shown

<<html> <head> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <title>Gallery</title> <!-- CSS only --> <link href="https://cdn.jsdel ...

Navigating through different components in Angular without using templates

Searching for a straightforward solution using Angular to manage routes. I have a webpage generated by the server featuring a basic Google map and some logic spread across three separate controllers. Now, I aim to integrate routing into this setup. Nothi ...

When dealing with errors in fetching JSON data, consider implementing a robust error handling strategy and

Is there a way to provide a fallback JSON string in case the fetch URL fails to connect? const Response3 = await fetch(`https://example.com/match/get?_=&id=${matchlist[2].id}`) ...

Adding design to distinct element after clicking a button

Struggling with a JS/Jquery issue on my portfolio website, I admit that I am still just an average programmer. My portfolio website has five buttons, each representing a different project. For each project, there is a corresponding text description and an ...

Failed Axios POST request on iOS devices

Attempting a straightforward ajax POST from domain1 to domain2 using Axios. This involves a cross-domain simple POST without requiring a PREFLIGHT (OPTIONS) call. The response returned by the application is a basic JSON string. This process functions smoo ...

Having trouble getting JavaScript to select a stylesheet based on time?

I am attempting to implement two different styles based on the time of day. Here is the code I am using to select the CSS file depending on the current time: <script type="text/javascript"> function setTimedStylesheet() { var currentTim ...

JavaScript Tutorial: Simplifying Character Ranges for Conversion

I am currently working on adapting code I found here to create a virtual keyboard for a foreign alphabet using an online textarea. Below is the modified code: <textarea id="txt"></textarea> <script src="https://ajax.googleapi ...

Is it possible for URLs in CSS Custom Properties to be relative to the CSS file where they are defined?

I have a CSS library with resources like images and fonts that can be accessed from anywhere via CDN. I am trying to create URLs for these resources as Custom CSS Properties, relative to the library. <!-- https://my.server/index.html --> <link rel ...

What is the best way to empty textfields following an ajax query in jquery?

Here's the jQuery function I'm using to perform an AJAX query: $("#add").click(function() { val1 = $('#add_lang_level').val(); val = $('#add_lang').val(); listitem_html = '<li>'; listitem_html ...

How can you apply color to {{expression}} text using AngularJS while also keeping all the text on a single line?

After writing the following code, I noticed that when I enter text into the input box, an output appears. However, I am now trying to find a way to color the output text while keeping it on the same line. <script src="https://ajax.googleapis.com/ajax ...