Smashed Blog Development

Tag Archive: css

jQuery CSS theme switcher

Comments Off

HTML:

<ul class="themeSwitch">
	<li><a href="#light" id="light" class="selected">Light</a></li>
	<li><a href="#dark" id="dark">Dark</a></li>
</ul>

jQuery:

//Theme switcher
$('.themeSwitch a').click(function(e) {
	//Get the ID from link
	id = $(this).attr('id');

	//Load alternate styles
	if (id == 'dark') {
		//Method 1: Swap out existing CSS included in head
		url = '/blog/wp-content/themes/smashedcrab/css/monokai.css';
		$('#syntax-css').attr('href', url);

		//Method 2: Change body class
		$('body').removeClass('light').addClass('dark');
	} else {
		//Must be light
		url = '/blog/wp-content/themes/smashedcrab/css/github.css';
		$('#syntax-css').attr('href', url);
		$('body').removeClass('dark').addClass('light');
	}

	//Remove any selected link
	$('.themeSwitch .selected').removeClass('selected');
	//Add 'selected' class to clicked link
	$(this).addClass('selected');

	//Prevent default link action
	e.preventDefault();
});

Mark active page with jQuery and CSS

Comments Off

This one is really handy. Sometimes you may need to change window.location.pathname, depending on how your URL structure works.

Assuming you have a menu set up in a list:

<ul id="nav">
	<li><a href="#">Link_1</a></li>
	<li><a href="#">Link_2</a></li>
	<li><a href="#">Link_3</a></li>
</ul>

Use the jQuery:

var url = window.location.pathname, 
urlRegExp = new RegExp(url.replace(/\/$/,'') + "$");
$('#nava').each(function(){
	if(urlRegExp.test(this.href.replace(/\/$/,''))){
		$(this).parents('li').addClass('active');
	}
});

And then some good old CSS:

#nav li.active a:hover {
	font-weight:700;
}

:focus support with jQuery

Comments Off

This is an oldie, but a goodie. I don’t find myself using this as much these days, but for when you need some old browser support for the CSS :focus property.

$('input[type="text"]').focus(function() {
    $(this).addClass("focusField");
    if (this.value == this.defaultValue){
        this.value = '';
    }
    if(this.value != this.defaultValue){
        this.select();
    }
});
$('input[type="text"]').blur(function() {
    $(this).removeClass("focusField");
});