Adding CSS class to div with unique ID - javascript

So, I am really new to CSS. I am developing a site for the company I work for using WordPress. I know, WordPress "NOOB ALERT."
Anyway, I am using the massive dynamic theme and was hoping to get some help. I created three CSS classes that I want to apply to three different divs that have unique ID's.
widget-column-1
widget-column-2
widget-column-3
And I want to add the following CSS classes to those divs.
footer-widget-1
footer-widget-2
footer-widget-3
respectively to their corresponding number. However, when I tried any of the following methods using the themes built-in "custom JS" editor, the CSS classes failed to apply to the divs. And yes, the CSS works, I manually added the classes in developer mode on Chrome and it gave me the following.
Screenshot of result w/ css
But, whenever I input any of the following JS solutions, the CSS class is not applied.
$(".widget-column-1").addClass("footer-widget-1");
$("#widget-column-1").addClass("footer-widget-1");
Neither of these worked, I also tried a few other solutions but can't remember them off the top of my head. Please try to keep in mind that I just started CSS two days ago and am still learning, I don't want my poor little head to get bashed in by some coding giant with a club made of XSS attacks.
CSS classes I am trying to apply

Looking at your screenshot, what would work for the first widget would be:
$('[widgetid="footer-widget-1"]').addClass("footer-widget-1");
But, in order for this to work, you'd have to place it in a script that gets loaded on every page you want this to happen. And you probably want to wrap it into a
(function($){
// your jQuery code here...
})(jQuery)
What I don't really understand is why are you trying to add this class, when you could use the existing class/id/attributes as selectors for the CSS you're trying to apply.
For example:
[widgetid="footer-widget-1"] {
/* CSS for #widget-column-1 here */
}
...or...
#widget-column-1 {
/* CSS for #widget-column-1 here */
}
If you add this to your active theme's style.css it's going to work.
As a side note, you'll probably find CSS Selectors and CSS Combinators useful. Also, in order to become efficient in CSS your code should apply. You'll need two things:
learn to inspect, using developer console of any major browser
learn CSS specificity. This will make you understand fast how strong (specific) your selectors need to be in order for a rule to apply, without breaking anything else.
You might also want to tour the Codex to make sure you understand how WordPress works.

I have lost count of the number of "professional" programmer's websites that are made with wordpress. I have also lost count of how many websites made by freelance developers who use wordpress. So, not exactly a "noob" thing.
As for your code, try running it on page load:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script> <1--
<script>
$(document).ready(function () {
$(".widget-column-1").addClass("footer-widget-1");
$("#widget-column-1").addClass("footer-widget-1");
});
</script>
Developers generally prefer to narrow down their selectors based on specificness, instead of adding !important. But I'll give you the option to use it, if you wish:
And if that doesn't work, I notice that most wordpress developers add:
!important
To the end of every CSS declaration... Basically, this adds priority to your CSS over the template's css.
So, here would be your new code:
.footer {
background: /*stuff here*/ !important;
background-repeat: /*stuff here*/ !important;
background-size: /*stuff here*/ !important;
background-position: /*stuff here*/ !important;
}

Related

Overwrite jQuery UI CSS

I have a little problem with jQuery UI at this time.
We use jQuery Accordions for our application and since our upgrade to jQuery UI 1.11.14 we experience a problem that causes any CSS we have written for Accordions to get overwritten by jQuery.
As far as I've understood this, jQuery UI activates itself after pageload and appends its styling. That leaves the question how I can add my own styling if jQuery always comes last. Any style inspectors shows that jquery-ui.min.css overwrites everything we have written before.
I know that !important exists but this is just bad practise and we want to avoid this or else we would append !important to about 20 rules or so which just looks terrible.
Edit:
Here is a screenshot from IE's F12 Console:
Here is a screenshot from IE's F12 Console http://puu.sh/lAoYJ/b3ed91b91c.png
Specificity matters a lot in CSS. Almost all the rules in jQuery UI do not use #ids. So that's a great advantage. ID takes higher precedence. So, when you wanna do something, for eg:
.col-md-5 {color: #f00;}
If this was already written in the bootstrap as:
.row .col-md-5 {color: #000;}
Then your code doesn't work. Give the body an id or a parent. So that way, you can target:
#id .col-md-5 {color: #f00;}
And that works well.

Toggle a website's color

I'm currently using a design that I made using the following tutorial to have both a black/white background on my website:
http://designshack.net/articles/css/lightsoff/
While this tutorial somewhat gets the job done (very sensitive to altering pieces of html/css around), I'm really looking for a much more elegant implementation. Is there any way to create a toggle'd switch using jquery or javascript that allows for changing the background color of an entire website?
I just picked up web programming as a hobby about a week ago so I know very little about javascript and jquery right now.
EDIT: I have a static site and I'm not too concerned on performance since the only person looking at this website 99.9% of the time will be me.
Write this in javascript
var i=1;
function myFun()
{
if(i%2==0)
document.body.style.backgroundColor="black";
else
document.body.style.backgroundColor="white";
i++;
}
in event of click
<button onclick="myFun()">Click me</button>
I hope you got your ans. :)
You could create a separate css file with styles defined for all the required elements in the page, and then add the css dynamically to the page based on the button click, or a radio select as shown below.
$('head').append('<link rel="stylesheet" href="style1.css" type="text/css" />');
and
$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
Here is a nice tutorial, which explains it
http://www.rickardnilsson.net/post/Applying-stylesheets-dynamically-with-jQuery
Code your website using whatever you prefer as the default color scheme. Then, create css for alternate color schemes that are under a theme subclass. For instance:
p,h1 {color:red;]
.blue-theme p,h1 {color:blue;}
Then just use javascript or server-side variables to add the "blue-theme" class to your body or root element tag. This also makes it easy to transition between themes if you apply a css transition!
It's not the most efficient in terms of load sizes, as your CSS file will be slightly larger, and performance is not optimal as adding a theme will cost processing time, but for general use I believe it's the best way to accomplish this.
jQuery is great for helping beginners add this type of functionality to websites. First, setup your CSS similar to this:
body {
background-color: #fff;
}
body.dark {
background-color: #000;
}
This sets the default css to white, and then using JavaScript you'll add a "click handler" to you button by referencing the buttons id attribute to change the class (and resulting color):
$('#yourButtonID').click(function() {
$('body').toggleClass('dark');
});
You'll want to make sure you include a copy of jQuery in a tag before you execute the above code on the page.
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.js"></script>
Using jQuery for just this single application might be overkill, but it is the easiest way to accomplish what you want without experience and it's a library you can do a lot more with if you dive deeper into it. Good luck!
I'm not going to give you the exactly code but definately look into some of the updating functions of javascript and implement css. Maybe load different css files as colors themes for your website.

How to remove jQuery Mobile styling?

I chose jQuery Mobile over other frameworks for its animation capabilities and dynamic pages support.
However, I'm running into troubles with styling. I'd like to keep the basic page style in order to perform page transitions. But I also need to fully customize the look'n feel of headers, listviews, buttons, searchboxes... Dealing with colors only is not enough. I need to handle dimensions, positions, margins, paddings, and so on.
Therefore I struggle with extra divs and classes added by jQuery Mobile in order to override them with CSS. But it is so time-consuming, and it would be way faster to rewrite css from scratch...
Is there a way to load a minimal jQuery Mobile css file ?
Or should I look towards an other mobile framework ? I need to handle page transitions, ajax calls, Cordova compatibility, and of course a fully customizable html/css...
Methods of markup enhancement prevention:
This can be done in few ways, sometimes you will need to combine them to achieve a desired result.
Method 1:
It can do it by adding this attribute:
data-enhance="false"
to the header, content, footer container.
This also needs to be turned in the app loading phase:
$(document).on("mobileinit", function () {
$.mobile.ignoreContentEnabled=true;
});
Initialize it before jquery-mobile.js is initialized (look at the example below).
More about this can be found here:
http://jquerymobile.com/test/docs/pages/page-scripting.html
Example: http://jsfiddle.net/Gajotres/UZwpj/
To recreate a page again use this:
$('#index').live('pagebeforeshow', function (event) {
$.mobile.ignoreContentEnabled = false;
$(this).attr('data-enhance','true');
$(this).trigger("pagecreate")
});
Method 2:
Second option is to do it manually with this line:
data-role="none"
Example: http://jsfiddle.net/Gajotres/LqDke/
Method 3:
Certain HTML elements can be prevented from markup enhancement:
$(document).bind('mobileinit',function(){
$.mobile.keepNative = "select,input"; /* jQuery Mobile 1.4 and higher */
//$.mobile.page.prototype.options.keepNative = "select, input"; /* jQuery Mobile 1.4 and lower */
});
Example: http://jsfiddle.net/Gajotres/gAGtS/
Again initialize it before jquery-mobile.js is initialized (look at the example below).
Read more about it in my other tutorial: jQuery Mobile: Markup Enhancement of dynamically added content
...or just use the official, theme-less version of the CSS built specifically to allow the design of a custom theme while maintaining all of jQuery Mobile functionality.
You don't have to fight with hacks and overrides all the time and you get a lighter CSS.
Win-win.
edit: Also answered here
To be honest i'm fairly disappointed that jQuery mobile didn't provide us with a relatively style-free starting kit, to work merely with what you have said: Ajax, transitions, cordova...
Overriding the generated css classes is absolute madness, but I have done some skunk work and I managed to reduce the uncompressed css file size from a whooping 233kb to merely 27kb, while keeping the important aspects of the css such as transitions, one-page viewing, etc. This way you start almost as you would start with an empty css file.
Perhaps I will upload the file on Github, if there's any demand for it. I wish to do some more testing to see that I didn't leave anything significant behind.
as of jQuery Mobile 1.4.0, the data-enhanced data attribute was added to most of components. Setting this as true attribute will cause jQuery mobile to ignore style enhancement for the component, so you'll have to style the element by your own.
additional information about this in the jQuery Mobile 1.4.0 release notes here
http://jquerymobile.com/upgrade-guide/1.4/
i m nô expert but i would love to share à weird method with you . Actually, it s very hectic task : what you need is to edit the jqm css line by line by deleting the property values just leave them blanks before ; you have just to look after the desired sections of the CSS file to adjust or delete value
Do not forget to attach your link rel of your own CSS at the head of your HTML page
I hope it will work for you

My styles get overridden by the html I get with ajax

I am building a mass mailer system where you can see a preview of the email before it is sent. I render the email html into a preview box using jquery -- $().html(theHtml).
Html emails use all inline css for their styles. When I fill the html, it overrides some of my css.
I am looking for a solution to completely stop this from happening. Is there any way to self contain the email html/css so it does not affect the entire document?
I understand that adding !important to my styles will do the trick, but it is not a very scalable option.
Thanks in advance.
Unfortunately !important is the only way to override an inline style - that's just how specificity works.
However you might be able to get around it by making all of the "wrapper" CSS (e.g. the CSS for YOUR page, not the HTML email preview) more specific by using IDs and classes etc so that their styles don't get overridden by generic style declarations embedded in the HTML email.
I'm a little confused though - are you trying to override "inline" styles (as in elements with the style="your css here" attribute) or embedded CSS (e.g. "your css here")? If it's the latter, just make important stuff more specific in your own CSS.
Some more info about specificity: http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/
Using an iframe as Sander suggested might be a simpler solution than trying to restructure your CSS specificity rules though.
Are you using the same class/id names for your website and the emails? This should not be the case.
I highly recommend using a pseudo-namespace for your CSS.
Basically, add an arbitrary prefix to your CSS that won't be contained in the inlined 3rd-party content: <div class='foo'> becomes <div class='myapp-foo'>
Having used this practice on our projects recently, it requires only a bit more discipline, but makes the app easier to manage for embedding other content.

How to keep user from seeing "ugly" HTML precursor when using jQuery UI and RequireJs?

I'm trying to adapt a jquery-ui codebase to use RequireJs, and I'm deploying it on a much slower (but scalable) virtualized cloud service than the dedicated host I was using before.
My pages are by default an ugly catastrophe of vanilla HTML. The only thing that brings this mess to life are calls to JavaScript functions, which give it the appropriate tab controls and layout. In fact, the page is laid out long and vertical...one section after another...before I call the .tabs() function which folds them up into a single unit with a horizontal control.
(Fairly confident I'm "doing it right" in the jQuery UI mindset. By not building the whole UI through code to start with, it can be at least looked at with JavaScript disabled. Though I doubt anyone is still using Lynx, there are issues of accessibility...or making sure your content is analyzable by search engines. I'll spare you my old man speech about how this is an absurdist way of achieving content/UI separation. :-/)
When I was using <script> tags to load my 3rd party library dependencies and the $(document).ready to run the jQuery UI voodoo, the user never saw the vanilla ugly HTML. Now that I'm using RequireJs, the page.js file lags and loads asynchronously after the HTML...waiting for libraries that aren't really needed for the DOMready handling. The slower server makes this look really awful.
I could of course use CSS styling to hide the ugliness at the outset, and overlay with a "Loading..." graphic until the UI was ready. That's what came to mind first, and a similar approach is suggested here:
Jquery UI interface looks ugly before document.ready
(Note: It seems like such a common problem that I'd almost think there'd be a RequireJs plugin that went ahead and did this. Is there?)
In any case, I didn't seem to have to worry about this before...and I'm wondering if I'm missing some simpler solution. How do you keep users from seeing "ugly" HTML if you're using RequireJs?
I'm with you that you should do some CSS wizardry and then in RequireJs's "kick it off" script, hide it. You should also consider SEO impact and JavaScript disabled scenarios.
Remember, at the end of the day, it's just HTML, CSS, and JavaScript. What ever templating / code generation system you use to get you there, at the end of the day, it's just HTML content, styled with CSS, and animated with JavaScript.
I'd argue that it makes more sense to use something like node-browserify to do all of your Javascript module requires and then stream down the single JS file to the end-user.
Why go through all of the TCP handshakes and HTTP headers to get the same thing at a much lower performance when the client is obviously not intended to be run in an offline mode?
Hey Doc, it hurts when I do this.
Well, then don't do that!
I'm having the same issue with Jquery Mobile and RequireJS.
I first tried following this tip and hid the "ugly HTML" by adding CSS:
.requireJS-init { visibility: hidden;}
.requireJS-init.done { visibility: visible;}
and assiging .requireJS-init when the page fires up and removing it once everything has been loaded by adding another class done (you could remove the initial class, too I guess).
However this causes two problems:
1. Users might have a blank page for a while depending on your content being loaded
2. IE8 fails, because (in my case) Jquery Mobile tries to focus on elements while they are still hidden.
I tried moving around the class form HTML to BODY to elements holding the page content, but nothing really worked.
A much easier CSS-only solution is this:
.ui-mobile-rendering:before {
width: 100%;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: block;
height: 100%;
z-index: 0;
background:#fff url(../images/ajax-loader.gif) no-repeat center center;
content: ""
}
The ui-mobile-rendering class is on the body while JQM does it's widget enhnacements. Once the page is done, the class is removed. By adding a fullscreen :before - in this case with the JQM loader as background image - you hide everything on the page until it's rendered. No need for visibility:hidden, IE8 doesn't complain (thank good, IE8 and FF3.6 know :before).

Categories

Resources