Tips for embedding two JavaScript functions in a single script source file?

I'm completely new to the world of JavaScript. Currently, I'm working on a web project where I want to dynamically change the styles of two div elements based on select/option values. Sadly, when I try to merge the codes together, it just won't cooperate.

Here's the code snippet:

<html>
<head>

<style>
div {
  width:100px;
  height:50px;
  border:1px solid Black;
  margin:10px; padding:6px;
}

select {
  width:150px;
  height:30px;
}
</style>
</head>
<body>
<div class="Box1" id="Box1"> This is the First Box. </div>
<div class="Box2" id="Box2"> This is the Second Box. </div>

// Rest of HTML and script omitted for brevity...

I attempted various methods but as far as I can tell, they all turned out incorrectly:

  1. Trying to link both source files.
  2. Efforts to consolidate them into a single script (either with function() or combining variables).
  3. Placing them as separate scripts within an HTML document.

EDIT: It seems to only affect changes in the second box.

EDIT: This is part of my efforts to create a web button generator on my alternate domain hosting site.

Answer №1

Let's consider a more efficient way to assign handlers in this situation. If you were dealing with a variable number of selectors, it could become quite cumbersome.

Setting that aside for now, the key to resolving your issue lies in not using change as the same variable name across both elements.

Furthermore, repeatedly declaring var change = ... within the same function is not allowed. Initially set the variable with var change = ..., and if you need to update its value later on, simply use change = ... without reusing var.

In your specific scenario, it's best to utilize two distinct variables until you can dynamically allocate event listeners to each element programmatically.

Your revised code should appear like this:

<script>
var change = document.getElementById('Box1');

document.getElementById('1stforeground').addEventListener('change', function(){
  change.style.color = this.value;
});

document.getElementById('1stfont').addEventListener('change', function(){
  change.style.fontFamily = this.value;
});

document.getElementById('1stbackground').addEventListener('change', function(){
  change.style.backgroundColor = this.value;
});

var change2 = document.getElementById('Box2');

document.getElementById('2ndforeground').addEventListener('change', function(){
  change2.style.color = this.value;
});

document.getElementById('2ndfont').addEventListener('change', function(){
  change2.style.fontFamily = this.value;
});

document.getElementById('2ndbackground').addEventListener('change', function(){
  change2.style.backgroundColor = this.value;
});

</script>

The reason why your initial code only affected the second box was due to continually reassigning the change variable. Each instance of:

change = document.getElementById('blah');
essentially overwrote all prior assignments to it.

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

The onClick event for a q-btn does not seem to be functioning properly when used

Inside the q-btn, there is a q-checkbox. Additionally, I included a div to style the text. <q-btn flat color="blue" class="full-width no-padding" @click="tog(item)" > <q-checkbox ...

"Revamp Your Layout with Bootstrap 4's Customized Sorting Feature

I'm exploring methods to rearrange items on mobile using the md and col- classes to achieve the following layout: On Desktop: [1] [4] [2] [5] [3] [6] [7] For Mobile: [1] [2] [3] [4] [5] [6] [7] Is there a way to accomplish this without reso ...

Here's a guide on executing both GET and POST requests using a single form

Currently, I am developing a web application which involves using a GET request to display checkboxes in a form. The selected data from the checkboxes needs to be sent back to the server using a POST request. However, I'm facing an issue with performi ...

Encountering a crash with the NativeDroid HTML5 JS css jQueryMobile template on iOS7

Recently, I began working on a mobile solution using the NativeDroid template, an HTML5 JS CSS template available at . However, a friend informed me that the template does not work on iOS7 devices. I tested it on multiple devices. Even when running the de ...

Issue: The hook call is invalid. In React Native, hooks can only be called within the body of a function component

While attempting to utilize useSelector within the component, I encountered an error message stating: Error: Invalid hook call. Hooks can only be called inside of the body of a function component. backgroundTasks.js: import axios from "axios"; i ...

Having trouble with col-span not working as expected in Tailwind CSS?

I have a grid layout with 9 buttons using grid-cols-2, leaving the last button in a single column. I want that final button to span across both columns using Tailwind CSS. Code for .btn : @tailwind base; @tailwind components; @tailwind utilities; @layer ...

Having trouble selecting links in the navigation bar

Just getting started with HTML/CSS and designing a website with buttons. Got some buttons up and running perfectly fine. But now, I'm working on a navigation bar with anchors inside. The problem is that while I can see the anchors when I open the webs ...

Experiencing hiccups in Angular testing when using Jasmine and Karma, specifically encountering errors with the router-outlet and failing component creation tests

I've built and successfully run an Angular app When running tests with ng test, I'm encountering errors related to component creation The console is showing errors indicating a failure to load router-outlet As an Angular test beginner, any sugges ...

Preventing a hyperlink from following its destination path

Hey there, I'm having trouble preventing a link from carrying out its default action. Here's the code I'm using: $("a.delete").on("click", function (e) { var container = $("#lightbox-background"); var lightbox = $("#lightbox"); ...

Preserving scroll position during page navigation in Next.js

Currently, I am working on a website using the Next.js boilerplate. Here is the routing code that I am using: import Link from 'next/link' <Link href={{ pathname: '/some-url', query: { param: something } }}> <div> ...

"Sorry, MongoDB seems to be having trouble with the pretty() function at the

Every time I attempt to extract information from a Mongodb database, an error keeps popping up: The problematic part of the code is located right here: ...

The app's connection issue persists as the SDK initialization has exceeded the time limit

We are currently facing an issue when trying to publish a new manifest for our app in the store. The Microsoft team in India is encountering an error message that says "There is a problem reaching the app" during validation. It's worth noting that th ...

Can I group data by "Month" in Tabulator JS while still retaining the full date information?

I am currently utilizing the Tabulator JavaScript library. I am aware that there is a group option available where I can group data based on certain fields in my dataset. One of the fields I have is a date field in the format MM/DD/YYYY. My objective is ...

localStorage access denied in IE11 on desktop mode, but not in metro mode

I am encountering an issue with a website that is built on Adobe AEM 5.6.1 and checks for localStorage accessibility. The problem arises when I try to access the site from the Desktop version of IE11 on an HP Elite Pad 900 running Windows 8.1 Pro, as it re ...

"What is the best way to manipulate arrays in vue.js using the map function

I'm currently dealing with a Vue code that incorporates anime.js. My code has grown substantially to over 1500 lines. In order for Stack Overflow to accept my question, I have only included 5 items of my sampleText, even though it actually consists of ...

When working with React and trying to update data using the useEffect hook, I encountered an issue with an Array data. Unfortunately, using map or Object.keys(data).map did not produce the desired results. Can anyone provide guidance on

After using the useEffect hook to update the data, I noticed that the data is an array when inspected in the DEV tools. However, when attempting to traverse the data using the map function, an error stating 'data.map is not a function' is returne ...

Is it possible to create a sharing button on Facebook that includes a JSON attachment?

I currently have some code that consistently generates the json needed for my facebook app's streamPublish FBJS call in the desired format. Now, I am experimenting with facebook.connect and I would like to reuse the same json. While exploring facebook ...

Design an introduction page with a responsive layout

After deciding to create a portfolio website, I came across an example that I liked and decided to replicate its style. However, I encountered an issue with responsiveness. When you resize the window on my site (https://olaolu.dev), everything changes size ...

Determining the height of child elements within a React component

One challenge I'm facing inside a React component is the need to calculate the total height of my child containers, specifically the three h3 elements, in order to accurately determine the height of my parent div during a transition animation. While I ...

Organizing Bootstrap Divisions in a Grid Pattern

I can't seem to figure out how to add a right margin to separate these div elements without the second one moving to a new line. It's probably something simple that I'm missing. https://codepen.io/jvern22/pen/GwQpgZ My layout consists of 2 ...