Switch the SPAN Class on and off while toggling this div

After trying multiple approaches, I'm still struggling to figure out how to toggle the class of a span from "die2" to "die3" and simultaneously toggle the display style of a div from 'block' to 'none'. Any suggestions or solutions? Essentially, when the page loads, an ad will be displayed. When you click the red x (die2), the ad should disappear and the red x should change to a green check box (die3). Here's the code snippet that successfully implements the div toggle:

<div id="mydiv" style="display:block">
<img src='http://www.test.com/mypopad.png' alt='' />
</div>

<a href="javascript:;" onmousedown="if(document.getElementById('mydiv').style.display == 'block'){ document.getElementById('mydiv').style.display = 'none'; }else{ document.getElementById('mydiv').style.display = 'block'; }"><span id="myspan" class="die2"><!-- --></span></a>

With gratitude to JKing's response and another class added to the stylesheet, I managed to solve the issue. Initially, the divHide class did not function as expected, so I introduced divShow and utilized similar logic for the span toggling. Thank you all!

<div id="mydiv" class="divShow">
<img src='http://www.northpointemobilehomesales.com/wp-content/gallery/support-images/big-daves-sidebar-ad_03.png' alt='' />
</div>

<a href="javascript:;" onmousedown="document.getElementById('mydiv').classList.toggle('divHide');document.getElementById('mydiv').classList.toggle('divShow');document.getElementById('myspan').classList.toggle('die2');document.getElementById('myspan').classList.toggle('die3');">
<span id="myspan" class="die2"><!-- --></span>
</a>

To address compatibility issues with Internet Explorer, I integrated Sven's script and resolved the problem by correcting the selector reference for #mydiv...

<script type="text/javascript">
  $("document").ready(function(){
    $("#myspan").click(function(){
      $(this).toggleClass("die2").toggleClass("die3");
      $("#mydiv").toggle();
   });
  });
</script>

<div id="mydiv" class="">
<img src='http://www.northpointemobilehomesales.com/wp-content/gallery/support-images/big-daves-sidebar-ad_03.png' alt='' />
</div>

<a href="#">
<span id="myspan" class="die2"><!-- --></span>
</a>

I will test this solution further to ensure it meets my requirements. Thanks for your help! :)

Answer №1

<script type="text/javascript">
  $("document").ready(function(){
    $("#myspan").click(function(){
      $(this).toggleClass("die2").toggleClass("die3");
      $("#mydiv").toggle();
    });
  });
</script>

That's all there is to it

Answer №2

Who needs jQuery when you can utilize an element's classList object for all your styling needs? The possibilities with classList are endless:

el.classList.add("myClassName")      //adds class (no effect if el already has that class)
el.classList.remove("myClassName")   //removes class (no effect if el doesn't have that class)
el.classList.toggle("myClassName")   //toggles class 

el.classList.contains("myClassName") //checks if el has the specified class

Take a look at this revised snippet of code, demonstrating how you can leverage classList - while it might not be exactly what you had in mind, it should steer you in the right direction.

<div id="mydiv" class="divHide">
    <img src='http://www.test.com/mypopad.png' alt='' />
</div>

<a href="javascript:;" onmousedown="document.getElementById('mydiv').classList.toggle('divHide');document.getElementById('myspan').classList.toggle('die2');document.getElementById('myspan').classList.toggle('die3');">
    <span id="myspan" class="die2"><!-- --></span>
</a>

(In this case, I'm using class toggling on the div to show/hide it, instead of manipulating the style attribute with if/else statements.)

Answer №3

My recommendation is to use jQuery:

mydiv.toggle() or mydiv.removeClass("hidden").addClass("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

NodeJS JSONStream causing memory exhaustion issue

I've encountered an issue while trying to stream a large JSON file (94mb in size) from an HTTP request to a local file using the JSONStream library in NodeJS. Despite setting a memory flag of 256mb with node --max-old-space-size=256 .\main.js, th ...

My goal is to store the received response in an array within an object

const data = [ { id: 1, user_name: 'john', phone_number: 5551234567 }, { id: 2, user_name: 'jane', phone_number: 5559876543 }, { id: 3, user_name: 'doe', ...

Two adjacent div elements containing text that seamlessly wraps and shares the same line

Here's a simple challenge for you - How can I make these two divs align on the same line: <div style="width: 200px; padding: 0; background-color: #f00; float: left; display: inline; ">Lorem ipsum dolor sit</div> <div style="margin-left ...

utilizing the entire string rather than just a portion

I was attempting to create a JavaScript jQuery program that vocalizes numbers based on some previously saved data. However, I encountered an issue where only the last number in the sequence was being played (the final character in the string). Below is t ...

Is there a way to dynamically create a property and assign a value to it on the fly?

When retrieving data from my API, I receive two arrays - one comprising column names and the other containing corresponding data. In order to utilize ag-grid effectively, it is necessary to map these columns to properties of a class. For instance, if ther ...

What is the best way to use Ajax GET after dropping an item with jQuery, and then append the result of a PartialView

In a webpage, I have <ul id="myPicturesAlbum" > <li id="picture1" data-index-number="image1"></li> <li id="picture2" data-index-number="image2"></li> <li id="picture3" data-index-number="image3"></li> ...

Exploring Bootstrap 4 Grid - Understanding the Difference Between .col-breakpoint and .col-number

I've recently decided to make the move from Bootstrap 3 to Bootstrap 4 and I'm taking a closer look at the changes in the grid system. https://getbootstrap.com/docs/4.0/layout/grid/ It explains: Thanks to flexbox, grid columns without a spe ...

Guide to performing a PUT request in jQuery

I need assistance with a script I am developing. It fetches JSON data from xyz.site and then posts it onto site.xyz. While I have successfully implemented the JSON data retrieval using jQuery's $.getJSON, I am encountering difficulties with making put ...

Ensuring Consistency Between States in AngularJS and UI-Router to Avoid Unnecessary Reload

In my ui-router setup, I have a 'parallel states' configuration that handles two different parts of the DOM (left and right) based on the URL and state. The right side always displays 'bar', while the left side alternates between baz an ...

Error encountered in Vue3: An uncaught TypeError occurred when attempting to "set" a property called 'NewTodo' on a proxy object, as the trap function returned a falsish

I encountered an error message: Uncaught TypeError: 'set' on proxy: trap returned falsish for property 'NewTodo' This error occurs when attempting to reset the input text value within a child component (FormAddTodo.vue). App.vue: expo ...

IE 7 textarea malfunctioning with word spacing issues

I have a website using the LAMP stack with a form that users fill out. Strangely, when I view the submitted form data in IE 7, it adds line breaks between each word. The form is simple with input elements and a text area. Submitting the form in FF3+, IE8, ...

display the table without providing a preview

Hey everyone, I am currently utilizing vue.js to develop a table and I am looking for a way to add a button that can print the data in the table without displaying a preview dialog. What modifications should I make to my javascript code in vue? Here is an ...

Issue with implementing a custom filter for currency in AngularJS code

I'm tackling a pretty straightforward task here. I just need to integrate a currency filter into the custom filter that I coded. Take a look at the code snippet below: var app = angular.module('testapp', []); app.controller('MainCt ...

Wordpress Debacle: Bootstrap Columns Clash

Currently, I am in the process of designing a unique theme. In my code, I have implemented a condition that generates an additional div with the class "row" after every three posts or columns are created. Everything seems to be working smoothly, except f ...

Steps for establishing a one-to-many relationship in my comment database table

I've inserted the following code into my articles migration: Schema::create('articles', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('user_id'); $table->foreign('user_id')- ...

The TypeScript inference feature is not functioning correctly

Consider the following definitions- I am confused why TypeScript fails to infer the types correctly. If you have a solution, please share! Important Notes: * Ensure that the "Strict Null Check" option is enabled. * The code includes c ...

Is there a way to bind the sortablejs results to the vue data?

How can I pass the result to data in Vue? I am confused with how to implement sortable features using Vue and SortableJS. The project utilizes Bootstrap-Vue.   <div>     <b-table v-sortable="sortableOptions" striped hover :items="items"> ...

Having difficulty positioning text within a div with a fixed height

I'm facing a challenge in aligning text at the center of a div. My goal is to horizontally center it, but position it slightly higher than the vertical center. The div has a fixed height of 45%. How can I achieve this layout? .galf { width : 100%; he ...

Eliminate any leading or trailing spaces around a string contained within a tag within a contenteditable div

I am working on a project to eliminate extra spaces before and after text within a bold tag. Functionalities: I developed a text editor where users can type text, select it, and apply bold formatting. Additionally, there is an HTML button that displays th ...

Formatting of large numerical values with jQuery

I have a huge table with numbers and other data. I want to color the large numbers based on their value in decimal, hundreds, thousands, and millions. For example: <tr> <td class="numColour">20,000,365.00 ISK</td> <td class="nu ...