I was just trying to make a condition in JQuery, if it’s false, then a message appears on the screen. Actually, I was trying to create a page to dynamically generate content from some other local pages. Clearly stating, I was trying to get generated reports from DU meter (a software to monitor bandwith), anyway that doesn’t matter at all. Let’s come to the point. Here’s my JQuery code:
$(document).ready(function() {
var table_count = $(document).find('table'),
sum = table_count.length,
files = ['DU_monthly.html table',
'DU_weekly.html table',
'DU_today.html table'
]
function DataCall () {
for (var a= 0; a < sum; a++) {
var pos = ($(table_count[a]).attr('data-serial'));
/* **************** The condition is here ****************** */
if (pos == 'table' + (a+1)) $(table_count[a]).load(files[a]);
else $('body').empty().prepend('<h1>Sorry, an error occured during data transfer.</h1>').css({
fontSize: 'xx-large',
fontWeight: 'bold',
fontVariant: 'smallCaps',
color: 'red',
fontFamily: 'Corbel, Consolas, Cambria, serif'
}).hide().fadeIn(1500);
}
}
DataCall();
});
Now as you can see, if the ‘else’ condition runs, the body will be emptied and an ‘h1’ will be added containing the message. The given css should be applied on the ‘h1’. But it’s not happening. I had an external CSS file that also had rules for ‘h1’ elements. Rather than following the given CSS rules in JQuery, it’s following that external CSS rules. But shouldn’t JQuery CSS rules override local/external stylesheet rules?
Confusing! by the CHAINING RULE of JQuery, the CSS should be applied to the h1. Any way, where should I put the word “!important”, in the style sheet, or the JQuery code. I want the JQuery CSS to override others, in this case using the !important in local/external sheet would be meaningless.
No you are effecting changes on the body as that is the selector you have originally targeted. To target the h1 that you just added you would need to do something like this (there may be better ways):
$('body').empty().prepend('<h1>Sorry, an error occurred during data transfer.</h1>'[B]).find($('h1:first')[/B]).css({
fontSize: 'xx-large',
fontWeight: 'bold',
fontVariant: 'smallCaps',
color: 'red',
fontFamily: 'Corbel, Consolas, Cambria, serif'
}).hide().fadeIn(1500);
Any way, where should I put the word “!important”, in the style sheet, or the JQuery code. I want the JQuery CSS to override others, in this case using the !important in local/external sheet would be meaningless.
I gave you a working example. The css just goes in the css filea nd you don’t need any css in the js. It’s usually best to avoid directly changing styles in jquery as really that is css’s job so just add a class with jquery and then you can always update the styles from the css without messing with scripts.
Both example above are working examples and will do what you wanted.