The jQuery click event to change the color function is functioning properly, but there seems to be an issue with

I'm having trouble changing the font-family using the code below, even though the color is changing properly. What am I missing here and how can I correct it?

$(document).ready(function(){
  $("body").on("click",".selectableColor", function(){
      var tColor = $(this).attr("data-color"); 
    $('.change').css('color','#'+tColor+'');
  });
  $("body").on("click",".fontBox", function(){
      var tStyle = $(this).attr("data-style"); 
    $('.change').css('font-family', tStyle); 
  });
});

HTML

    <div class="change_area_header" style="overflow: hidden; outline: currentcolor none medium;" tabindex="2">
      <div class="selectableColor" style="background-color:#ffebee" data-color="ffebee"></div>
      <div class="selectableColor" style="background-color:#ffcdd2" data-color="ffcdd2"></div> 
    </div>
    <!--Font Family-->
    <div class="change_area_header" style="overflow: hidden; outline: currentcolor none medium;" tabindex="4">
      <div class="fontBox" style="font-family: 'Montserrat', sans-serif;" data-style="'Montserrat', sans-serif;">MontSerrat</div>
      <div class="fontBox" style="font-family: 'Aleo', serif;" data-style="'Aleo', serif;">Aleo</div>
      <div class="fontBox" style="font-family: 'Raleway', sans-serif;" data-style="'Raleway', sans-serif;">Raleway</div>
    </div>

Check out the demo on codepen.io

Answer №1

Eliminate the semi-colons within the font selectors as follows:

Change

data-style="'Montserrat', sans-serif;"

To

data-style="'Montserrat', sans-serif"

resulting in:

<!–– ... -->
 <div class="fontBox" style="font-family: 'Montserrat', sans-serif;" data-style="'Montserrat', sans-serif">MontSerrat</div>
<!–– ... -->

Link to Pen : https://codepen.io/ijasnijas/pen/wNvPXa

Answer №2

Avoid using semicolons at the end of

data-style="'Montserrat', sans-serif;"

Instead, use

data-style="'Montserrat', sans-serif"

Answer №3

It's important to properly handle character escaping. Your code should look something like this:

$('.change').css('font-family', 'Montserrat, sans-serif;')

A simpler solution would be to use

$('.change').css('font-family', 'Segoe UI')
in your specific case.

Instead of including the entire font chain in

data-style="'Raleway', sans-serif;"
, consider just using data-fontname="Raleway" and setting up the font chain within your code.

Answer №4

It seems that there may be a more efficient way to approach problem-solving based on the code I observed. For example, instead of binding the click action to the body, you could select the specific tag using jQuery and then attach the action callback to it.

In addition, it is advisable to define CSS classes separately rather than inline in the HTML code. This allows for easier manipulation of classes in the markup without directly assigning style properties to elements, which can make debugging more challenging. This approach can help identify and resolve issues more effectively.

I recommend organizing your code in a cleaner manner, such as the example provided below. You can use this sample as a guide to enhance your entire project:

$(document).on('ready', function(){
  var resultEl = $('.result');
  $('.blue').on('click', function(){
    resultEl.removeClass('red').addClass('blue');
  });
  $('.red').on('click', function(){
    resultEl.removeClass('blue').addClass('red');
  });
});
.result {
  font: normal 20px arial;
  margin-bottom: 20px;
}

.blue {
  color: #f00;
  font-family: tahoma;
  margin-bottom: 20px;
  cursor: pointer;
}

.red {
  color: #00f;
  font-family: monospace;
  margin-bottom: 20px;
  cursor: pointer;
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<div class="result">The Result of color and font</div>
<div class="blue">color&font</div>
<div class="red">color&font</div>

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

Preventing an image from being repeated when using Canvas drawImage() without having to clear the entire canvas

How can I prevent multiple instances of the same image from smearing across the canvas when drawing it? The platforms seem to stick together and not separate properly. Why do I have to clear the entire rectangle for everything to disappear? Does anyone ha ...

Error: VueJS mixins do not include the property definition

I've been trying to incorporate Mixins into my Vue.js code, but I've run into a few issues :/ Here's the current code for two test modules : ErrorBaseMixin.vue <script> import ErrorAlert from './ErrorAlert'; expor ...

Ways to randomize an array without any repeating elements with the help of jQuery?

let numbers = [5, 12, 18, 23, 30]; What is the most efficient way to randomize the order of these numbers in a new array without any duplicates? Example: newArr = [18, 30, 5, 12, 23]; ...

Navigating with Node.js: Understanding how to showcase the response data within a list structure

I am brand new to working with node.js and I'm looking to display the data I receive as a response on my webpage. Currently, I can see the output in my console. Is there a way to show this data on my actual page? GET Request: app.get('/bestell_ ...

Encountering a START_ARRAY token during a spring ajax call

Here is an example of a JSON object: [ { "usernameid": [ "2", "7" ], "phaseid": [ "2", "7" ], "weekstartdate": "2014-11-02" } ] In my controller, I am trying ...

Unable to execute simple demo on the threejs.org platform

As I delve into learning three.js, I came across some examples worth exploring. One specific code snippet I attempted to execute can be found here. Unfortunately, all I saw was a blank black screen. To troubleshoot, I adjusted the three.js source to my lo ...

Transfer results of SQL query from PHP to JavaScript array

Every day, I manually update a JavaScript variable in the following way: <script> var data = [ ['Austria','IBM','8284927','UF93NV', '10'], ['Spain','Dell&ap ...

"Taking cues from Instagram's web/desktop design, we have created

When you view someone's instagram page on a desktop or pc, the search bar is designed to float left when clicked, allowing text to be entered for searching. If no text is entered in the search field, the search icon and placeholder return to their ori ...

Determine whether a response is not received within 8 seconds

One of the methods in my Angular component is responsible for returning data Here is a snippet of that method getRecognitionById() { this.loaderService.show(null, true); forkJoin( this.vendorWebApiService.getRecognitionById(this.executiveCh ...

Yep, implementing conditional logic with the `when` keyword and radio buttons

I seem to be encountering an issue with my implementation (probably something trivial). I am utilizing React Hook Form along with Yup and attempting to establish a condition based on the selection of a radio group. The scenario is as follows: if the first ...

What is the best way to generate an array of objects by extracting specific properties from another array object?

Here is the information provided: const cocktail = [ { "idDrink":"13070", "strDrink":"Fahrenheit 5000", "strGlass":"Shot glass", "strInstructions":&qu ...

I successfully coded a function without utilizing the function key, but unfortunately I am encountering difficulties when trying to output the

I have created a function without using the function keyword. The function should take the age above 15 and push it into an array. I have been able to do that, but I am struggling to print the result. Can anyone help me with this? my code <script> ...

Exploring the syntax of typescript when using createContext

Just starting out with typescript and I have some questions. Could someone break down the syntax used in this code snippet for me? What is the significance of having two groups containing signIn, signOut, and user here? Is the first group responsible fo ...

Sticky positioning is not maintaining its position at the top

I've noticed a strange behavior where, when I scroll down, the yellow box goes on top of the blue box. I have set both boxes to have a position sticky so that they should stay in place and not overlap. However, I want only the orange box to be scrolla ...

Design interactive Vue form with customized questions based on user response

I am looking to dynamically create a form with conditional fields. The structure of the form is stored in an object called Q. Below is an example of a Vue component that utilizes bootstrap-vue. <template> <div> <div v-for="q of ...

Obtain the class attribute of a CSS element with whitespaces using PHP's XML/HTML

I'm currently facing an issue with the PHP XML DOM parser. When parsing HTML from the real world, I noticed that many elements have multiple CSS classes due to spaces in the 'class' attribute. However, when using getAttribute() on a DOMNode, ...

Pictures displayed in a bootstrap carousel are not completely filling up the entire carousel space

I recently started working with Ruby and decided to use the refile Gem for uploading multiple photos. I wanted to showcase the photos in a Carousel format using Bootstrap carousel. However, when I display the photos, they don't fill the carousel windo ...

Generate a dynamic kendo dropdown with data sources assigned in separate methods

Creating a kendo dropdown list dynamically based on the number of received id's is presenting a challenge. A method has been implemented to loop through each id and generate a corresponding dropdown with that id. These dropdowns are not all generated ...

Create a personalized and distinct name following the submission of data into multiple text fields either through Nuxt/Vue or by utilizing pure JavaScript

In my new app, users can register packages and then participate in a ballot session where the package will be assigned to someone else. To make this process smoother, I want each ballot session or box to have a unique Ballot ID attached to it. For example ...

The elements of the second flex item should also be arranged in a line next to each other

<script src="https://use.fontawesome.com/2a2c577e07.js"></script> <div class="parent-flex"> <div class="class1">Class 1</div> <div class="class2"> <img src="http://farm4.static.flickr.com/3140/3506456511_43787 ...