Modifying my code: utilizing toggle() and toggleClass() at the moment

Confusion in Code Communication

The following IDs lack proper communication:

  • #html-button
  • #css-button
  • #js-button
  • #result-button

To address this, I introduced a new class called .selected. The code functions well with the current setup. However, removing selected from any of these IDs necessitates adding additional CSS and setting "display: none" for corresponding viewport containers:

  • #html-container
  • #css-container
  • #js-container
  • #result-container.

I acknowledge that using if statements is one approach, but I also seek alternative methods or functions to streamline this process. I value clear, efficient, and minimalistic code over unnecessary checks and loops.

My current method involving toggle() and toggleClass() does not seamlessly handle manual removal of the .selected class without simultaneously adding display: none to my ID container divs.

Sometimes, I may want to change the default open ID containers upon app launch, which necessitates manually removing the .selected class.


I would appreciate fresh perspectives on different approaches to tackle this issue.


Access My Code on CSSDeck

Javascript Section

    $('.code-container').css('height', $(window).innerHeight() - 39 + "px");
$(window).resize(function () {
    $('.code-container').css('height', $(window).innerHeight() - 39 + "px");
});


$("[id$=button]").click(function () {

    $(this).toggleClass('selected');

    
    var viewID = "#" + $(this).html() + "-container";
    $(viewID).toggle();

    var viewSize = $(window).innerWidth()/$('.selected').length;
    $(".code-container").css("width", viewSize);
}
);

$('#run').click( function() {
    var html = $('#htmlCode').val();
    var css = $('#cssCode').val();
    var js = $('#jsCode').val();
    $('#iframe').contents().find("html").html("<style>" + css + "</style>" + html);
});

HTML Section

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0>

    <title>Interactive Code Editor</title>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
    <link rel="stylesheet" href="style.css" />

</head>

<body>

    <div id="wrapper">

        <div id="header">
            <p id="logo">CodeEditor</p>
            <nav>
                <ul>
                    <li id="html-button"    class="toggle selected no-highlight">html</li>
                    <li id="css-button"     class="toggle selected no-highlight">css</li>
                    <li id="js-button"      class="toggle selected no-highlight">js</li>
                    <li id="result-button"  class="toggle selected no-highlight">result</li>
                </ul>
            </nav>
            <div id="run" class="no-select">Run</div>
        </div>

        […]

CSS Section

/* Global Settings */
* { padding: 0; margin: 0;}
body {
    font-size: 14px;
    font-family: sans-serif;
}
.no-highlight {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

/* Header Logo Toggles and Buttons */
#header {
    width: 100%; height: 28px;
    background-color: #222;
    padding: 4px;
}
#header #logo {
    color: #fff;
    font-weight: 500;
    position: absolute;
    left: 10px; top: 4px;
    font-size: 1.5em;
    line-height: 28px

}

[…]

Answer №1

Your approach is commendable, but there are areas where your implementation can be enhanced.

Allow me to suggest some improvements:

  1. Avoid relying on the innerHtml of buttons for identification purposes. Instead, consider using a new data-pane attribute or even utilizing the id by removing the "-button" substring.
  2. Organize your code with named functions for better structure and readability.
  3. In your CSS, set all .container elements to be hidden by default and display only those associated with "selected" buttons during application initialization.

Here is a DEMO

Key Changes Made

HTML

I have demonstrated the removal of the selected class from the first item. Additionally, I have included the data-pane attribute:

<li id="html-button"    class="toggle no-highlight" data-pane="html">html</li>
<li id="css-button"     class="toggle selected no-highlight" data-pane="css">css</li>
<li id="js-button"      class="toggle selected no-highlight" data-pane="js">js</li>
<li id="result-button"  class="toggle selected no-highlight" data-pane="result">result</li>

CSS

I have added display: none; property.

.code-container {
    width: 25%;
    float: left;
    position: relative;
    display: none;
}

JS

While major parts have been rewritten, below are the new additions.

This snippet displays all selected panes upon app initialization:

  $('.selected').each(function() {
    var pane = $(this).data('pane');
    showPane(pane);
  });

Below code provides necessary information for toggling:

  var pane = $(this).data('pane');
  var isSelected = $(this).hasClass('selected');

  if(isSelected) {  
    hidePane(pane);
  } else {
    showPane(pane);
  }

The following functions handle displaying and hiding panes along with updating the view:

function showPane(pane) {
  $('#' + pane + '-button').addClass('selected');
  $('#' + pane + '-container').show();
  updateContainers();
}

function hidePane(pane) {
  $('#' + pane + '-button').removeClass('selected');
  $('#' + pane + '-container').hide();
  updateContainers();
}

function updateContainers() {
  var viewSize = $(window).innerWidth() / $('.selected').length;
  $(".code-container").css("width", viewSize);
}

You'll notice that manual use of display: none; is no longer necessary.

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

I am dealing with too many unnecessary whitespaces on my website. Can someone advise me on how to rectify this

https://i.sstatic.net/1PoMd.png My image should explain the issue, but I'll provide more details. Lately, as I build my webpage, I've noticed an excessive amount of whitespace on the right side that serves no purpose for me. Despite my efforts t ...

Tips for adjusting the font size in Bootstrap 5 using the fs-* class with SASS variables

Is it possible to customize the Bootstrap 5 fs-* class in Sass? I attempted to follow the documentation, which outlines how to modify h-* classes like h5-font-size, but there is no specific information on customizing the fs-* class. ...

Unable to Modify Data in Text Fields Using JQuery Dialog

I am currently working on a project that involves displaying multiple tables and utilizing JQuery dialog boxes to modify and add data to these tables. The implementation of the dialog box, along with populating it with content from the table and saving the ...

The code functions correctly on JSfiddle, however it is not executing properly on my website

When I tried to implement the code from this jsfiddle link: http://jsfiddle.net/mppcb/1/ on my website (), it didn't work as expected: Here is the HTML code snippet: <form id="myform" novalidate="novalidate"> <input type="text" name="fi ...

What is the process for choosing a dropdown menu on a website created with JavaScript, specifically utilizing Selenium in Python3?

I need help with selecting the item "Short_Budget_Report" from a website's HTML code using Selenium and the Select module. Here is the relevant section of the HTML code: <input id="WD51" ct="CB" lsdata="{1:'20ex', ...

Guide to using jQuery to input a multi-line text into a field

Dealing with a value that spans multiple lines obtained from PHP has been challenging due to the structure of textareas. The standard method of inserting it into the textarea is not feasible in this case. I resorted to using jQuery for this purpose, but ...

Clicking on the image does not result in a larger image being displayed

Currently working on an assignment that requires a modal pop-out to display larger versions of photos when clicked, with the option to go back using the X button. Unfortunately, I'm facing issues with the X button not functioning properly and images n ...

Tips for positioning an inline label and input field in an Angular application using CSS and HTML: How to align the label to the left and the input

I'm currently developing an Angular form with multiple label-input field combinations. I have managed to style the labels and input fields with inline block so that they appear on the same row. However, I am facing a challenge in aligning the label to ...

Adaptive video player for complete YouTube experience

Is there a way to incorporate a YouTube video as the background of a div, similar to how it is done on this site, using a <video> tag and ensuring that the video "covers" the entire div without any empty spaces while maintaining its original ratio? ...

Key Enhancements for Functional Stateless Components

How can I accurately assign a key in a functional component, specifically using the 'key' keyword instead of just a general index? I am attempting to use Map in a functional component to generate a list of another element. However, when I try to ...

When subjecting an ASP.NET application to load testing with 100 users using JMeter, an error related to jQuery functionality is

As part of load testing for my asp.net application using jmeter, I am simulating only 100 users. The issue arises when jQuery is present on the page at "Scripts/jquery.min.js" and an error occurs in 20% of cases as shown below: Sample Result :- Thread N ...

What is the best way to establish the render() method for an 'arrow' component?

I came across the following code snippet: const CoolComponent = props => { ... I am looking to add a render() function to it: render() { console.log('Hello world'); return ( <Bar foo={true} {...propz} ...

Using Xpath to target elements based on attributes and retrieving the values of another attribute

I am trying to extract the datetime attribute value from each li element that contains an attribute type with the value of standard. However, my current code is resulting in an error. Here is the snippet: <li datetime="2019-06-03T14:45" offset="-135" t ...

The result of the $.post() request is back

In my current code, I am using a jQuery $.post function like this: $.post('/test', json_data, function(data) { result = data }); This function is being used in a validation process where the return value (data) contains either true or false ...

Using JavaScript's if-else statements is akin to a checkbox that is always in its

When working with checkboxes, I can retrieve the state (checked or unchecked) in the browser developer console using $("#blackbox").prop('checked')or $('#blackbox').is(':checked'). I have tried both methods. For example, if I ...

What causes the footer to disappear in Rails with Bootstrap?

Within my application.html.erb file, my setup is pretty standard: <html class="h-100"> !head, title, scripts, styles, stylesheets removed for this example here on stackoverflow! <body class="d-flex flex-column h-100"> <!-- Dropdown St ...

Using jQuery's .addClass() method

Here is a code snippet that I've been looking at: <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <script> $(document).ready(function(){ var index=5; $("ul li: ...

How to Disable Envmap in Three.js

Incorporating an environment map into my scene has been a successful endeavor. The lines of code involved are: sceneTarget.environment = envMap; and sceneTarget.background = envMap; Now, I am seeking guidance on how to disable the environment altogether. ...

Tips for looping through multiple states within a single table

I need help with combining data from two different states, campaigns and stats, into a single table. The campaigns state includes sr no, campaign id, campaign name, and campaign status, while the stats state includes reach, sent, delivered, views, clicks ...

Switch from using $.ajax to $post when making requests in Rails

After the code snippet below, an ajax call is used for a post request. Now I want to switch from $.ajax to $.post. How do I modify the data in accordance with $.post? $.ajax({ method: "POST", url: "get_object", dataType: "json", data: { ...