Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use addClass in jQuery to call a CSS class written in another file

I want to call a CSS class written in a CSS file from a JQuery function (external file too).

It doesn't work I wonder why :

jQuery :

/// <reference path="jquery-1.7.1.js" />
/// <reference path="jquery-1.7.1-vsdoc.js" />
/// <reference path="main_style.css" />
    function gg() {
        alert("zombie");
        $("p").addClass("blood");
    };

CSS :

.blood
{
    color: Aqua;
    background-color: Red;
    border: 2;
    font-weight: bold;
}

I added a reference to CSS file in the jQuery file and I don't uderstand why it doesn't find it and doesn't change all the paragraphs.

But the "gg" function is reached because I see the zombie alert.

HTML :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.7.1-vsdoc.js" type="text/javascript"></script>
<link href="Scripts/main_style.css" rel="stylesheet" type="text/css" />
<script src="Scripts/mon_script.js" type="text/javascript"></script>


<title></title>
</head>
<body>
<div>
<p>This is the first paragraph</p>
<p id="4">This is the second paragraph</p>
<p>This is the third paragraph</p>
<p class="blood">This is the fourth paragraph</p>
<input type = "button" value="Hi" onclick="gg()" />

</div>
</body>
</html>

1 Answers

You need to add a link to the stylesheet main_style.css in the html document (i.e. aspx file in ASP.NET) that includes your jquery script. The reference path you specified is just for supporting IntelliSense.

The stylesheet link in your HTML file would look like this if both css file and html file are in the same relative position (otherwise use a relative path to the css file):

<LINK href="main_style.css" rel="stylesheet" type="text/css">
like image 78
BrokenGlass Avatar answered Dec 13 '25 09:12

BrokenGlass