Using Javascript to change CSS file being used - javascript

I am attempting to change the CSS of the page whenever a list is being clicked. However whenever I try and do so the browser just shows the CSS as text and doesn't actually use it for the page. Looked at a bunch of answers on here but cant get any to work.
<ul>
<li>Character</li>
<li>Send Message</li>
<li>Messages</li>
<li>View Blog</li>
<li>History</li>
<li><a id="test" href="styles.css" rel="stylesheet" type="text/css">Dark Theme</a></li>
<li><a id="test2" href="styles2.css" rel="stylesheet" type="text/css">Red Theme</a></li>
<li><a id="test3" href="styles3.css" rel="stylesheet" type="text/css">Light Theme</a></li>
<li>Logout</li>
</ul>
<script>
$(document).ready(function() {
$("#test").attr("href", "styles.css");
});​
$(document).ready(function() {
$("#test2").attr("href", "styles2.css");
});​
$(document).ready(function() {
$("#test3").attr("href", "styles3.css");
});​
</script>
EDIT:
I have tried doing what user neil said to do but whenever I implement the following I am unable to click on the list entries. The cursor does not change to the little hand with a finger you usually get hovering over links. Clicking does nothing.
<li><a class="test" data-src="styles.css">Dark Theme</a></li>
<li><a class="test" data-src="styles2.css">Red Theme</a></li>
<li><a class="test" data-src="styles3.css">Light Theme</a></li>
<li>Logout</li>
</ul>
<script>
$(document).ready(function(){
$(".test").on('click', function(){
$('head').append('<link rel="stylesheet" href="' + this.getAttribute('data-src') + '" type="text/css" />');
});
});
</script>
EDIT2:
I have implemented another users solution which still doesnt work on mine. If you are going to downvote my post please tell me why atleast, I would really like to fix this. My new code:
<!DOCTYPE html>
<html>
<head>
<link href="styles.css" rel="stylesheet">
</head>
<body>
<div id="header">
<h1>D20-TABLEKEEPER</h1>
<form action="blurb.php">
<input type="submit" value="BLURB" size="21">
</form>
</div>
<ul>
<li>Character</li>
<li>Send Message</li>
<li>Messages</li>
<li>View Blog</li>
<li>History</li>
<li>Dark Theme</li>
<li>Red Theme</li>
<li>Light Theme</li>
<li>Logout</li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">
$(document).ready(function(){
$(".changeStyle").click(function(){
var style = $(".changeStyles").attr('data-src');
$('head').append('<link href="'+ style +'" rel="stylesheet">');
});
$(".changeStyle1").click(function(){
var style = $(".changeStyles2").attr('data-src');
$('head').append('<link href="'+ style +'" rel="stylesheet">');
});
$(".changeStyle1").click(function(){
var style = $(".changeStyles3").attr('data-src');
$('head').append('<link href="'+ style +'" rel="stylesheet">');
});
});
</script>

With jQuery I can offer no real assistance but with vanilla javascript it is quite easy to do. Assign an id to the original stylesheet so that it can be targeted easily, use querySelectorAll to identify the links used to switch css and assign an event listener to each. The code below also stores the selected value in localStorage so that the user's choice persists across pages / sessions.
Assume three stylesheets ( all in same directory as current page, otherwise paths need to be added ) named styles.css,styles2.css and styles3.css which, for pure simplicity are as follows:
styles.css
----------
html, html *{
background:red;
color:white;
}
styles2.css
-----------
html, html *{
background:blue;
color:yellow;
}
styles3.css
-----------
html, html *{
background:green;
color:orange;
}
<!doctype html>
<html>
<head>
<title>css style switcher - no jQuery</title>
<link id='style' href='styles.css' rel='stylesheet'>
<script type='text/javascript'>
function bindEvents(){
var css=document.getElementById('style');
var col=document.querySelectorAll('a.changeStyle');
/* iterate through collection and assign listener */
for( var n in col )if( col[n].nodeType==1 ) col[n].onclick=function(e){
e.preventDefault();/* prevent jumping to top of page etc */
var el=typeof(e.target)!='undefined' ? e.target : e.srcElement;
/* assign style attributes */
css.href=el.dataset.style;
css.rel=el.dataset.rel;
css.type=el.dataset.type;
/* store reference to style selected in localstorage */
localStorage.setItem( 'style', el.dataset.style );
};
/* if there is a reference to the user's css choice in storage, assign it */
if( localStorage.getItem( 'style' )!=null ) css.href=localStorage.getItem( 'style' );
}
document.addEventListener( 'DOMContentLoaded', bindEvents, false );
</script>
</head>
<body>
<ul>
<li><a href='character_sheet.php'>Character</a></li>
<li><a href='send_message.php'>Send Message</a></li>
<li><a href='view_messages.php'>Messages</a></li>
<li><a href='view_blog.php'>View Blog</a></li>
<li><a href='history.php'>History</a></li>
<li><a href='#' class='changeStyle' data-style='styles.css' data-type='text/css' data-rel='stylesheet'>Dark Theme</a></li>
<li><a href='#' class='changeStyle' data-style='styles2.css' data-type='text/css' data-rel='stylesheet'>Red Theme</a></li>
<li><a href='#' class='changeStyle' data-style='styles3.css' data-type='text/css' data-rel='stylesheet'>Light Theme</a></li>
<li><a href='index.php'>Logout</a></li>
</ul>
</body>
</html>

First of all, I don't see anywhere where you're binding a click
$(document).ready(function(){
$(".test").on('click', function(){
$('head').append('<link rel="stylesheet" href="' + this.getAttribute('data-src') + '" type="text/css" />');
});
});
And your html
<li><a class="test" data-src="styles.css">Dark Theme</a></li>
<li><a class="test" data-src="styles2.css">Red Theme</a></li>
<li><a class="test" data-src="styles3.css">Light Theme</a></li>
This way, on any .test click, you append a <link> for the css to your head.

You need to add it in head section of the page.
Eg
$("a").click(function () {
$('head').append('<link rel="stylesheet" href="style.css" type="text/css" />');
});
Please refer this tutorial
http://www.rickardnilsson.net/post/Applying-stylesheets-dynamically-with-jQuery

I tried it. And, it was working.
HTML Page
<html>
<head>
<link href="styles.css" rel="stylesheet">
<title>asd</title>
</head>
<body>
<a class="changeStyle1" data-src="style.css">style1</a>
<a class="changeStyle" data-src="style1.css">style1</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".changeStyle").click(function(){
var style = $(".changeStyle").attr('data-src');
$('head').append('<link href="'+ style +'" rel="stylesheet">');
});
$(".changeStyle1").click(function(){
var style = $(".changeStyle1").attr('data-src');
$('head').append('<link href="'+ style +'" rel="stylesheet">');
});
});
</script>
</body>
</html>
style.css
a {color:red;}
style1.css
a {color:green;}

Related

Materializecss sidenav not working

I am trying to get the sidenav to work for the Materializecss framework.
MATERIALIZECSS http://next.materializecss.com/getting-started.html
SIDENAV DEMO http://next.materializecss.com/sidenav.html
MY CODEPEN https://codepen.io/gregoryksanders/pen/RxoyqB
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.2/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/
</head>
<body>
<ul id="slide-out" class="sidenav">
<li><i class="material-icons">cloud</i>First Link With Icon</li>
<li>Second Link</li>
<li><div class="divider"></div></li>
<li><a class="subheader">Subheader</a></li>
<li><a class="waves-effect" href="#!">Third Link With Waves</a></li>
</ul>
<i class="material-icons">menu</i>
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.2/js/materialize.min.js"></script>
</body>
3 Days trying to figure this out :/ so any help is welcomed.
The problem is that you should initialize the side-nav in Javascript code like this
var elem = document.querySelector('.sidenav');
var instance = new M.Sidenav(elem);
// with jquery
$(document).ready(function(){
$('.sidenav').sidenav();
});
now your code will work perfect
var elem = document.querySelector('.sidenav');
var instance = new M.Sidenav(elem);
// Initialize collapsible (uncomment the lines below if you use the dropdown variation)
// var collapsibleElem = document.querySelector('.collapsible');
// var collapsibleInstance = new M.Collapsible(collapsibleElem, options);
// Or with jQuery
$(document).ready(function(){
$('.sidenav').sidenav();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.2/js/materialize.min.js"></script>
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.2/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/
</head>
<body>
<ul id="slide-out" class="sidenav">
<li><div class="user-view">
<div class="background">
<img src="images/office.jpg">
</div>
<img class="circle" src="images/yuna.jpg">
<span class="white-text name">John Doe</span>
<span class="white-text email">jdandturk#gmail.com</span>
</div></li>
<li><i class="material-icons">cloud</i>First Link With Icon</li>
<li>Second Link</li>
<li><div class="divider"></div></li>
<li><a class="subheader">Subheader</a></li>
<li><a class="waves-effect" href="#!">Third Link With Waves</a></li>
</ul>
<i class="material-icons">menu</i>
<!-- Compiled and minified JavaScript -->
</body>
On the materialize website, this code is given to initialize Sidenav bar
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.sidenav');
var instances = M.Sidenav.init(elems, options);
});
but You modify This code and remove option in var instance and now code look like and you should paste this code in your script tag or your javascript file
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.sidenav');
var instances = M.Sidenav.init(elems);
});
Now I explain what is the problem in upper code that given on the materialize website
in code, variable instances give 2 arguments 1st argument is elems and 2nd argument is the option that is not defined in your code so you remove the option argument in this code to solve this problem
Initialization is the most important thing when using materialize.js, for example i want to initialize a carousel.
// Javascript
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.carousel');
var instances = M.Carousel.init(elems, options);
});
// Or with jQuery
$(document).ready(function(){
$('.carousel').carousel();
});

What is wrong with my .click() event?

My problem is the .click event below. The 'nav' and '#closemenu' div hide as expected on document ready, but the click event won't work to save my life. Either I'm missing something embarrassingly small (which I hope is unlikely because I copy/pasted the code from the jQuery API page and then changed only the ID and alert) or else I have no idea what my issue is. Any help is much appreciated.
Here's my code:
$(document).ready(function() {
$('nav').hide();
$('#closemenu').hide();
$('#menuicon').click(function() {
alert('Hello, test');
});
});
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<header>
<h1>Page Title Here</h1>
<div id="menuicon">
<img src="mobile_menu.png">
</div>
<nav>
<ul>
<a href="">
<li class="upCase">Projects</li>
</a>
<a href="">
<li clas s="upCase">Profile</li>
</a>
<a href="">
<li class="upCase">Contact</li>
</a>
</ul>
</nav>
<div id="closemenu">
<p>X</p>
</div>
</header>
</body>
Why don't you just add the event directly like this
For multiple div use the below
$( "#menuicon" ).bind({ click: function(){ alert ();}
});

Change ul li parent color

I have this code in HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Form</title>
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="script.js"></script>
<link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<ul class="cars_menu">
<li>Audi
<ul>
<li class="highlight">A4</li>
<li>A6</li>
<li>A3</li>
<li>A5</li>
</ul>
</li>
<li>Volkswagen
<ul>
<li>Golf IV</li>
<li>Golf VI</li>
<li>Golf V</li>
<li>Jetta</li>
</ul>
</li>
<li>BMW
<ul>
<li>E36</li>
<li>E60</li>
<li>E70</li>
<li>Z4</li>
</ul>
</li>
</ul>
</body>
</html>
CSS code:
.highlight {
color: red;
}
And my script file:
$( "ul.cars_menu li" ).click(function() {
$( this ).toggleClass( "highlight" );
});
Anyone know, how to change the color of AUDI, if I click on A4, A6 it should set the color of A4 AND AUDI to red and if for example I click on GOLF IV it needs to change of Volkswagen and GOLF IV to red and so on.
Anyone could help me with this? Appreciate, guys :)
Please change the html code to
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Form</title>
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="script.js"></script>
<link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<ul class="cars_menu">
<li>Audi</li>
<li>
<ul class="model">
<li>A4</li>
<li>A6</li>
<li>A3</li>
<li>A5</li>
</ul>
</li>
<li>Volkswagen</li>
<li>
<ul class="model">
<li>Golf IV</li>
<li>Golf VI</li>
<li>Golf V</li>
<li>Jetta</li>
</ul>
</li>
<li>BMW</li>
<li>
<ul class="model">
<li>E36</li>
<li>E60</li>
<li>E70</li>
<li>Z4</li>
</ul>
</li>
</ul>
</body>
</html>
Jquery code to
$( "ul.model li" ).click(function() {
$( this ).parent().removeClass( "highlight" );
$( this ).toggleClass( "highlight" );
$( this ).parent().parent().prev('li').toggleClass( "highlight" );
});
Hope it will works!!!.
you need to wrap your jQuery in a :
$(document).ready(function() {
$('ul.cars_menu li').click(function() {
$( this ).toggleClass( "highlight" );
});
});
Reason for this - you need to wait for the DOM to finish loading before you can set the events on the elements further down the page...
$(document).ready event is when the DOM is finished loading & can be manipulated...
Editing to include js fiddle with some examples on how this can be done:
http://jsfiddle.net/7gdzLgam/
The answer on how to target parent elements using jquery that was the original question still applies to example above.
You should be able to use .parent() for this.
Something like:
$( this ).parent().toggleClass( "highlight" );
you can check the value of the li clicked by doing
$( "ul.cars_menu li" ).click(function() {
if ($( this ).text() == 'A4'){
//change css
}
});
The DOM elements will not be created when the js file is downloaded. Your javascript is correct but either you need to include your
<script src="script.js"></script>
at the end of body tag so that it will work.
This is because when the javascript is loaded it checks for the dom element which you have specified in the js file. It will not be able to find the element since the dom is not completely created. So it just neglects it.
Or else wrap the javascript inside
$(document).ready(function(){
//Your code here
});
so that js will not be executed unless the dom elements are created.

javascript function to pull html div into master.html div

Got a bit of a problem... basically using this statement in html with a ul menu to activate it.....
<div id="subnav" >
<ul>
<li id="subone">Definitions</li>
</ul>
</div>
</div>
<script src="jquery.js"></script>
<script type="text/javascript">
$(function(){
$("#subnav ul li a") .click(function(e){
e.preventDefault()
$('#content2').load($(this).attr('abc.html') + ' #content2');
});
});
</script>
<div id="content2">
</div>
......... This does nothing and can't seem to work out why....Can someone please tell me where I am wrong here. BTW the abc.html page simply has ....
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="whatis.css" />
</head>
<body>
<div id="content2"><p>this is a test </p></div>
<div id="content3"><p>Here comes some content </p></div>
</body>
</html>
any ideas people ??
cheers,
Greg.
Try this:
$('#content2').load('abc.html #content2');
.attr('abc.html') attempts to return the value of the attribute abc.html... so that would work if your a looked like this:
<a abc.html="something">Definitions</a>
(though that wouldn't be a valid attribute)
Now if your a looked like this:
Definitions
You could do this:
$("#subnav ul li a") .click(function(e){
e.preventDefault()
$('#content2').load($(this).attr('href') + ' #content2');
});

how to use javascript onclick event handler for same class of anchor elements

This is my javascript:
Here i grab data using ajax get request and call this function:
function fetch_user_data(data) {
$(user_board['results']).each(function(attributes,value){
$('.main_container').append(
'<div class="pin" id='+attributes+'>\
<div class="holder">\
<a class="image" href="" title="Photo number 1" pin_id='+ attributes +'>\
<img src="'+ value['profile'] + '" />\
</a>\
<p class="desc">' + value['name'] + '</p>\
<ul id="pin_actions">\
<li id="awe"></li>\
<li id="cof"><a href="#" onClick="onTabAction('+value['user_id']+'); return false;" ></a></li>\
<li id="ban"><a href="#" onClick="onTabAction('+value['user_id']+'); return false;" ></a></li>\
</ul>\
</div>'
);
});
}
function onTabAction(id,action) {
console.log(id);
console.log(action);
}
Here is a problem, my data contains 33 objects, and then according to object there are 33 html boxes belong to person profile. I attached onclick event handler in anchor tag and get user id through custom function which is onTabAction. Along with id i want to get a string like: onTabAction('+value['user_id']+',actionstr) but when i call this function and print output in console.log: it prints user id once and string equal to object quantiy like li#actionstr. In short I would like to get both string and id and make an url to query on other url. Please help me on this stuff, also if i get string and id i have to remove that anchor from main page as i place that anchor on other page.
Here is a working example, with the code you posted I can't make a working example because most of it is missing:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title>Example</title>
<style type="text/css">
.clickable{
cursor:pointer;
}
</style>
<script type="text/javascript" src="jquery-1.9.0.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var someData=["one","two","three"],
i=0,
user_id="my user id",
$main=$('.main_container');
for(i=0;i<someData.length;i++){
$main.append(
"<h1>"+someData[i]+"</h1>\
<ul id=\"pin_actions\">\
<li class=\"clickable\" data-action='awe'>awe</li>\
<li class=\"clickable\" data-action='cof'>cof</li>\
<li class=\"clickable\" data-action='ban'>ban</li>\
</ul>"
);
}
$main.attr("data-userID",user_id);
//attach onclick
$('.main_container').find("li").on("click",onTabAction);
});
function onTabAction(e) {
console.log("userID:",this.parentElement.parentElement.getAttribute("data-userID"));
console.log("action:",this.getAttribute("data-action"));
}
</script>
</head>
<body>
<div class="main_container">
</div>
</body>
</html>

Categories

Resources