Dynamically switching between bootstrap.css theme's - javascript

I am trying to switch between a dark & light theme I have created on my MVC application.
My _Layout.cshtml page loads the default theme I have created below
<link id="theme" rel="stylesheet" href="~/lib/bootstrap/dist/css/Original.css">
I have created the below buttons to switch between the themes below
<button id="light">Light</button><br />
<button id="dark">Dark</button>
My two other bootstrap themes are located in lib > bootstrap> dist > css >
I have the below js in my botstrap.js file
$('#dark').click(function () {
$('link[href="~/lib/bootstrap/dist/css/Dark.css"]').attr('href', '~/lib/bootstrap/dist/css/Dark.css');
});
$('#light').click(function () {
$('link[href="~/lib/bootstrap/dist/css/Dark.css"]').attr('href', '~/lib/bootstrap/dist/css/Light.css');
});
Not sure if I am making some obvious error but any help on this is appreciated.

Here it is in VanillaJS, check also if the href on the link tag resolves to CSS File correctly.
const darkBtn = document.querySelector('#dark');
const lightBtn = document.querySelector('#light');
const linkTag = document.querySelector('#theme');
darkBtn.addEventListener('click', () => {
linkTag.setAttribute('href', '~/lib/bootstrap/dist/css/Dark.css')
});
lightBtn.addEventListener('click', () => {
linkTag.setAttribute('href', '~/lib/bootstrap/dist/css/Light.css')
});

You probably need following code:
$('#dark').click(function () {
$('#theme').attr('href', '~/lib/bootstrap/dist/css/Dark.css');
});
$('#light').click(function () {
$('#theme').attr('href', '~/lib/bootstrap/dist/css/Light.css');
});
Your code is looking for a link-element where the href literally starts with ~/. In your razor page the href starts with this string. But ASP.NET replaces this with the path for the content-root, so for the browser, the href does not start with this string.

I downloaded Pieterjan solution and it began to work after I added event.preventDefault() like that:
$(document).ready(function () {
$('#dark').click(function () {
event.preventDefault();
$('#dynamicCss').attr('href', '/css/site-dark.css');
});
$('#light').click(function () {
event.preventDefault();
$('#dynamicCss').attr('href', '/css/site-light.css');
});
});
But website displays light theme again after refreshing the page.

Related

Move to top on click of button

I am using intro.js in my code to implement the walkthrough. I want to implement a sceanrio where on clicking the done button(.introjs-donebutton) the page should scroll to the top but with this code It is not happening. Can anyone please help me with this one?
//$('.col-new-four').attr('id','essentials');
const intro = introJs();
intro.setOptions({
steps:[
{
element:'#featured_apps_2_0',
intro:'welcome'
},
{
element:'#myTopnav',
intro:'Quickly access the apps and portals you need on and off the clock.'
},
{
element:'.slideshow-container',
intro:'This space features topics you care about the most.'
},
{
element:'.card',
intro:'Stay up-to-date on trending stories.'
},
{
element:'#stepextra',
intro:'View your recommended and favorite pages.'
},
{
element:'#step4',
intro:'Find promotional content, latest additions and more here.'
},
{
element:'#essentials2',
intro:'Learn about what’s trending with your favorite topics.'
},
{
element:'.col-new-7525',
intro:'Explore benefits, tools and new features available to you.'
}
]
})
$('.introjs-donebutton').click(function() {
$(window).scrollTop(0);
});
function callintro(){
intro.start();
console.log("called intro")
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intro.js/4.2.2/intro.min.js"></script>
I assume that you want to scroll the client view page to top on clicking a button. if so you can use this code
HTML
<div class="button-parent">
<button type="button" class="button-to-top">Click Here</button>
</div>
jQuery
$(document).ready(function () {
$('.button-to-top').on('click', function () {
$('body').scrollTop(0);
});
});
Don't Forget to add jQuery cdns to your html header file. If it's not working share your html code. we will look forward
Using pure javascript, no framework
window.scrollTo({ top: 0, behavior: 'smooth' })
So i used this and It started running fine, the reason being the button was dynamically being created after the inital page load, so this should work
$(document).on("click", ".introjs-donebutton", function(){
$(document).scrollTop(0);
})
function upsideItem() {
$(document).ready(function(upsideItem) {
$('.button-to-top').on('click', function(upsideItem) {
console.log(button-to-top)
$('body').scrollTop(0);
});
});
}

Have to double-click on tabs to get tab content

I have tabs on a page that are giving me trouble. I think it is in the js code. Sometimes you have to doubleclick on the tabs, sometimes you don't.
This is using HAML in Rails, which I am not as familiar with. I also didn't write the original code. I am taking over on a project.
Here are the codes:
HAML
#myTabs
%ul.tab-buttons.tab-buttons--boxed.tab-buttons--left.js-tabs.nav-tabs
%li.active.tab-button
%a#tab1.tab-button-link.active{"data-toggle" => "tab", "data-projects" => "not_archived"} Current Projects
%li.tab-button
%a#tab2.tab-button-link{"data-toggle" => "tab", "data-projects" => "archived"} Archived Projects
.tab-content
#tab1C.container
%ul.list-project
= render #projects
#tab2C.container
%ul.list-project
JS
$('.js-tabs li a:not(:first)').addClass('inactive');
$('.container').hide();
$('.container:first').show();
$('.js-tabs li a').click(function(){
var that = this;
var t = $(that).attr('id');
$.get("/projects", {projects: $(that).data("projects")}, function(){},'json')
.done(function(data){
var projects = data.projects;
if($(that).hasClass('inactive')){
$(that).removeClass('inactive');
$(that).addClass('active');
$('#'+t+'C .list-project').html(projects);
$('.container').hide();
$('#'+ t + 'C').fadeIn('slow');
} else {
$(that).removeClass('active');
$(that).addClass('inactive');
$('#'+t+'C .list-project').html(projects);
$('.container').hide();
$('#'+ t + 'C').fadein('slow');
};
$('.open-popup-link').magnificPopup(magnificPopupOptionsPermissionEmail);
})
});
I tried to show the codes in codepen but it isn't showing accurately.
Codepen
Are you finding that you have to double click if you just entered the page, but single click if you refresh the page?
If so, then turboloading may be the problem. A common fix is as follows:
var ready;
ready = function() {
// add your functions and calls here
}
$(document).ready(ready);
$(document).on('page:load', ready);

Correct way to use window.location.href in Polymer 1.1

In the index's head I have:
// hashbang is set to true in routing.html
<script type="text/javascript">
if (window.location.href === "/users") {
console.log('Hey you!');
}
</script>
I need to implement some class bindings based on window.location but I'm testing to make sure it works in polymer. Does it? I does not work for me. When I go to localhost:3000/#!/users, noting in console.
Update:
If you're using page.js with the Polymer starter kit, then all the pages of your app are loaded on the first load.
In this starter kit, changing route with Page.js will display the need page and add display: none to hide the other pages.
For example, in your app/index.html, you should have something like this:
<iron-pages attr-for-selected="data-route" selected="{{route}}">
...
<section data-route="home">
...
</section>
<section data-route="users">
...
</section>
<section data-route="user-info">
...
</section>
...
</iron-pages>
The route parameters on the iron-pages element is set by Page.js in app/elements/routing.html:
page('/', function () {
app.route = 'home';
});
page('/users', function () {
app.route = 'users';
});
page('/users/:name', function (data) {
app.route = 'user-info';
app.params = data.params;
});
page('/contact', function () {
app.route = 'contact';
});
So if the route matches /users for example, then Page.js will set app.route = 'users';, and the iron-pages Polymer element will display the section with data-route="users" and hide the other ones without reloading anything, and thus not reloading your script.
But actually, since you're using Page.js, it'd be easier to integrate your code in the routing.html file like so:
page('/users', function () {
app.route = 'users';
console.log('Hey you!');
});
page('/users/:name', function (data) {
app.route = 'user-info';
app.params = data.params;
console.log('Hey ' + data.params.name);
});
page('/contact', function () {
app.route = 'contact';
console.log('Contact page');
});
You could start by trying to debug, for example, try logging the window href:
console.log(window.location.href);
Which should return:
http://localhost:3000/#!/users
Then you can have more insight on what your problem is! ;)
Indeed, window.location.href gives you the full URL, and it's supposed to do so (with Polymer or not).
On the other hand, window.location.hash returns everything in the url starting from the # character, giving you #!/users, so you could try:
<script type="text/javascript">
// Slice(2) to get rid of '#!'
if (window.location.hash.slice(2) === "/users") {
console.log('Hey you!');
}
</script>
Side note:
If you have query parameters after the #, like so:
localhost:3000/#!/users?number=42&name=value
window.location.href will then be #!/users?number=42&name=value
If you also want to get rid of the query parameters ?number=42&name=value in such a case, you could write:
<script type="text/javascript">
if (window.location.hash.slice(2).split("?")[0] === "/users") {
console.log('Hey you!');
}
</script>

Using jQuery plugins in Meteor

I have been trying to add a jQuery plugin to Meteor but Meteor refuses to let the plugin work client side.
The example is I have this plugin that allows me to shuffle a bunch of divs around called jQuery Shuffle but when I call the following script in the head or from an external file it does not execute. It could be the plugin not publishing functions but it is client side so that makes no sense. I have verified that javascript and jQuery is working through a few console.log() command tests and those seem to work in external files or in the head wether they are inclosed in a jQuery function or not. Here is the code I am trying to use with jQuery Shuffle:
(do take note that this script also is using a few other plugins that appear not to be working either)
$(document).ready(function () {
var hash = window.location.hash.substr(1);
// Puts hash into search field
if (hash !== "") {
$("#search").val(hash);
$("#search").focus();
$('#search').keyup();
}
/* initialize shuffle plugin */
var $grid = $('#grid');
var $gridn = $('#gridn');
$grid.shuffle({
itemSelector: '.item',
group: 'alll'
});
$gridn.shuffle({
itemSelector: '.item',
group: 'news'
});
/* detects a news post */
if (hash.indexOf("news") > -1) {
$('#alll').removeClass('active');
$('#news').addClass('active');
$('#n-news').addClass('active');
$grid.shuffle('shuffle', 'news');
}
/* reshuffle when user clicks a filter item */
$('#filter a').click(function (e) {
e.preventDefault();
window.scrollTo(0, 0);
// set active class
$('#filter a').removeClass('active');
$(this).addClass('active');
// get group name from clicked item
var groupName = $(this).attr('data-group');
// reshuffle grid
$grid.shuffle('shuffle', groupName);
$gridn.shuffle('shuffle', groupName);
var n_catagories = ["n-v", "n-am", "n-av", "n-gd", "n-d", "comic", "blog"];
n_catagories.forEach(function (n_selectedcat) {
if ($("#" + n_selectedcat).hasClass("active")) {
$('#news').addClass('active');
//console.log(n_selectedcat)
}
});
});
// Sorting options
$('.select-options').on('change', function () {
var sort = this.value,
opts = {};
// We're given the element wrapped in jQuery
if (sort === 'date-created') {
opts = {
reverse: true,
by: function ($el) {
return $el.data('date-created');
}
};
} else if (sort === 'title') {
opts = {
by: function ($el) {
return $el.data('title').toLowerCase();
}
};
}
// Filter elements
$grid.shuffle('sort', opts);
});
// Advanced filtering
$('.search').on('keyup change', function () {
var val = this.value.toLowerCase();
window.scrollTo(0, 0);
$grid.shuffle('shuffle', function ($el, shuffle) {
// Only search elements in the current group
if (shuffle.group !== 'all' && $.inArray(shuffle.group, $el.data('groups')) === -1) {
return false;
}
var text = $.trim($el.find('.item-tags').text()).toLowerCase() + $.trim($el.find('.hidden').text()).toLowerCase();
return text.indexOf(val) !== -1;
});
$gridn.shuffle('shuffle', function ($el, shuffle) {
// Only search elements in the current group
if (shuffle.group !== 'all' && $.inArray(shuffle.group, $el.data('groups')) === -1) {
return false;
}
var text = $.trim($el.find('.item-tags').text()).toLowerCase() + $.trim($el.find('.hidden').text()).toLowerCase();
return text.indexOf(val) !== -1;
});
});
//REMOVE AND HIDE HANDELER
var $nnitems = $('.nnotice');
$(".nnotice-button").click(function () {
Cookies.set('hidennotice', 'true', {
expires: 31557600
});
});
if (Cookies.get('hidennotice') == 'true') {
$grid.shuffle('remove', $nnitems);
}
$(".nnotice").click(function () {
$grid.shuffle('remove', $nnitems);
});
//Auto Shuffle
$(".social-toggle").click(function () {
$(".social-stuffs").slideToggle("slow");
setTimeout(function () {
var catagories = ["alll", "v", "am", "av", "gd", "d", "news", "n-v", "n-am", "n-av", "n-gd", "n-d", "comic", "blog"];
catagories.forEach(function (selectedcat) {
if ($("#" + selectedcat).hasClass("active")) {
$grid.shuffle('shuffle', selectedcat);
}
});
}, 1000);
});
});
When not enclosed in Meteor, this script works as expected.
I have tried loading the JS files for the plugins by calling them normally through <script type="text/javascript" src="directory/somescript.js"></script> and by loading the scripts through the /client directory meteor uses to process files that are going to the client. It automatically loads these files in a <script> when put here. Even with Meteor loading them it seems not to work. I don't know if it is because the functions inside the plugins need to be published or if it is just no possible to use these kinds of plugins/apis with Meteor.
This is a working, unfinished version of the site without Meteor (and that has missing files and an unfinished color scheme)
Edit:
Basically I just need to be able to load a jQuery plugin somehow and then load the script to control it. That is what I am having trouble doing.
Using plugins like query could be a little tricky on meteor, example you are using
$(document).ready(function () {});
And its ok but i prefer to work with
Meteor.startup(function () {
});
Reference here Stack Question about onReady and Startup
Also some people prefer to use the Template.myTemplate.rendered ) function(){}
and its works (on my case works), and also try to use some Timeouts
You are not getting anything errors on the console, because nothings wrong happens all DOM elements were created, i face this problems many times using Carrousels, dynamic list from codrops etc.
If you have your web/project on some github repo or working in some cloud host Service like nitrous.io i could help you
Safest way is to deliver the plugin as a package and initialise it in template.rendered
I had this problem with a jquery plugin.
My html code was:
<head>
<meta charset="utf-8">
<!-- Plugin JQuery -->
<script src="js/jquery.easing.min.js"></script>
</head>
<body>
{{main}}
</body>
Then I put the script after {{main}} template and it works. The script is loaded after all javascript meteor packages:
<head>
<meta charset="utf-8">
</head>
<body>
{{main}}
<!-- Plugin JQuery -->
<script src="js/jquery.easing.min.js"></script>
</body>

excluding a page from javascript

I have a swipe to do back script for my ios web app that I have running across every page but what I want to know how is to exclude from affecting the first page that shows up. The script is this
<script>
$(document).bind('swiperight', function () {
history.back();
});</script>
How would exclude a page that has a hypothetical id of "home"?
I'm assuming you're using jQuery mobile (Apologies if you're not), you could use $.mobile.activePage to check if you're at home:
http://jquerymobile.com/demos/1.2.0/docs/api/methods.html (At the bottom)
<script>
$(document).bind('swiperight', function () {
if ( $.mobile.activePage !== 'home' )
history.back();
});
</script>
The general principle would be this:
<script>
var id = // get your hypothetical id from somewhere;
if(id !== "home") {
$(document).bind('swiperight', function () {
history.back();
});
}
</script>
Without any more information on where the hypothetical id is coming from it's difficult to be more specific than that.
$(document).bind('swiperight', function () {
if (!$('body#home').length === 0) {
history.back();
// ... anything else
}
});
You could also use: if (!$('#page.home').length === 0) if it's going to be a class on a containing element, if ($('#page').hasClass('home')) is a bit more of solid jQuery-y way of doing it too.

Categories