i have a website http://news.homepage119.biz/. I want to make the site display same in mobile as it displays in desktop. But i want to make a button to switch the responsive in mobile. I mean i don't want to load it responsively first in mobile but i will be able to toggle the responsive as i clicked on a button. I have designed the button in my website but i don't know how to make it work as i wanted. The website is already responsive. So, please help me to solve this problem.
You can put your media queries in a separate file and use javascript on click method to dynamically add/remove that file.
http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml
function createjscssfile(filename, filetype){
if (filetype=="js"){ //if filename is a external JavaScript file
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
}
else if (filetype=="css"){ //if filename is an external CSS file
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
return fileref
}
function replacejscssfile(oldfilename, newfilename, filetype){
var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist using
var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
var allsuspects=document.getElementsByTagName(targetelement)
for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(oldfilename)!=-1){
var newelement=createjscssfile(newfilename, filetype)
allsuspects[i].parentNode.replaceChild(newelement, allsuspects[i])
}
}
}
replacejscssfile("oldscript.js", "newscript.js", "js") //Replace all occurences of "oldscript.js" with "newscript.js"
replacejscssfile("oldstyle.css", "newstyle", "css") //Replace all occurences "oldstyle.css" with "newstyle.css"
Related
On the add page of a new Plone Page i want to suggest a title to the user derived from the Folder title by adding it into the title form field.
What is the best practice on implementing that behavior in my Plone instance?
An alternative solution can be to use Javascript, respectively jQuery:
(function($) { $(document).ready(function() {
// A Dexterity-based document is added:
if( window.location.href.endsWith('/++add++Document') ) {
// Grab the parent's title of the current title-tag's content:
var title = $('title')[0].innerHTML.split(' — ')[0]
// Prefill the new document's title-field with the parent's title:
$('#form-widgets-IDublinCore-title').val(title)
}
// An Archetypes-based document is added:
if( window.location.href.indexOf('/portal_factory/Document/') > -1 ) {
var parentUrl= document.referrer
var parentTitleEleId = 'parent-fieldname-title'
// Provide ele to load parent's title into:
var loadEle = document.createElement('span')
// Load parent's title into ele:
$(loadEle).load(parentUrl + ' #' + parentTitleEleId, function() {
// After loading finished, fetch parent-title of ele, remove
// trailing spaces and set it into the new doc's title-field:
$('#title').val(loadEle.childNodes[0].innerHTML.trim())
// Thy had served y'er purpose, vanish:
loadEle.remove()
});
}
});})(jQuery);
More to MonkeyPatching can you find in the Docs. Another solution is, you can register your own AddForm and set the Value of the Textline-Widget. To create a Custom AddForm look at the Docs
You can monkeypatch or subclass the Basic metadata behavior to modify the behavior of _get_title: https://github.com/plone/plone.app.dexterity/blob/master/plone/app/dexterity/behaviors/metadata.py#L350-L351
Meteor merges all (s)css files together as part of the build process and generates a single css file called /merged-stylesheets.css?biglongnumber
I'm using TinyMCE in a Meteor app and I want the content within the TinyMCE window to use the same css as the page it's on. TinyMCE has the ability to do this:
tinyMCE.init({
content_css : '/myStyles.css'
});
So I want to get the path to that merged stylesheet so I can pass it to TinyMCE. Is there a way to do this?
You can get the URL of the CSS files on the current page using the browser DOM, then make a comma-separated list of them and give it to TinyMCE. The following gets only the CSS files matching the current domain (& port and scheme):
//Get CSS files being used
var schemeDomainPort = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
var cssFiles = '';
for (var i = 0; i < document.styleSheets.length; i++) {
if (document.styleSheets[i].href && document.styleSheets[i].href.indexOf(schemeDomainPort) === 0) {
cssFiles += cssFiles ? ',' + document.styleSheets[i].href : document.styleSheets[i].href;
}
}
//Configure TinyMCE
$scope.tinymceOptions = {
content_css: cssFiles,
...
}
I was hoping anyone could give some input on this,
I'm creating a meteor app in which I would like to use bootstrap to creating the admin environment, but have the visitor facing side using custom css. When I add the bootstrap package to my app using meteor it's available on every page, is there a way to restrict the loading of bootstrap to routes that are in '/admin' ?
When you add bootstrap package it's not possible. You can, however, add bootstrap csses to public directory and then load them in a header subtemplate that will only be rendered when you're in the dashboard.
EDIT
But then how would you go about creating seperate head templates?
Easy:
<head>
...
{{> adminHeader}}
...
</head>
<template name="adminHeader">
{{#if adminPage}}
... // Put links to bootstrap here
{{/if}}
</template>
Template.adminHeader.adminPage = function() {
return Session.get('adminPage');
}
Meteor.router.add({
'/admin': function() {
Session.set('adminPage', true);
...
}
});
DISCLAIMER: I am unsure of a 'meteor way' to do this, so here is how I would do it with plain JS.
jQuery
$("link[href='bootstrap.css']").remove();
JS - Credit to javascriptkit
function removejscssfile(filename, filetype){
var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist from
var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
var allsuspects=document.getElementsByTagName(targetelement)
for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
}
}
removejscssfile("bootstrap.css", "css")
However, doing that would complete remove it from the page. I am not sure whether meteor would then try to readd it when a user goes to another page. If that does not automatically get readded, then you have an issue of bootstrap not being included when someone goes from the admin section to the main site, which would break the look of the site.
The way I would get around that would be to disable and enable the stylesheets:
Meteor.autorun(function(){
if(Session.get('nobootstrap')){
$("link[href='bootstrap.css']").disabled = true;
}else{
$("link[href='bootstrap.css']").disabled = false;
}
});
There my be other bootstrap resources which may need to be removed, take a look at what your page is loading.
To use jQuery in the same way but for the javascript files, remember to change link to script and href to src
From my tests, Meteor does not automatically re-add the files once they have been removed so you would need to find some way of re-adding them dynamically if you want the same user to be able to go back and forth between the main site and the admin site. Or simply if the http referrer to the main site is from the admin, force reload the page and then the bootstrap resources will load and everything will look pretty.
P.s. make sure you get the href correct for the jQuery version
If somebody is interested in including any js/css files, I've written a helper for it:
if (Meteor.isClient) {
// dynamic js / css include helper from public folder
Handlebars.registerHelper("INCLUDE_FILES", function(files) {
if (files != undefined) {
var array = files.split(',');
array.forEach(function(entity){
var regex = /(?:\.([^.]+))?$/;
var extension = regex.exec(entity)[1];
if(extension == "js"){
$('head').append('<script src="' + entity + '" data-dynamicJsCss type="text/javascript" ></script>');
} else if (extension == "css"){
$('head').append('<link href="' + entity + '" data-dynamicJsCss type="text/css" rel="stylesheet" />');
};
});
}
});
Router.onStop(function(){
$("[data-dynamicJsCss]").remove();
});
}
Then simply use:
{{INCLUDE_FILES '/css/html5reset.css, /js/test.js'}}
in any of your loaded templates :)
I am trying to read the pages CSS using a chrome extension. This is what i have in my content script :
var allSheets = document.styleSheets;
for (var i = 0; i < allSheets.length; ++i) {
var sheet = allSheets[i];
var src = sheet.href;
var rules = sheet.cssRules || sheet.rules;
}
For some reason the rules are always empty. I do get all the CSS files used in the 'src' variable. But the rules always come as null.. Its working when I try it as a separate javascript on a HTML page. But fails when I put it up in the content script of my chrome extension. Can somebody lemme know why?
Well thats the Why, but for fun and interest (never done anything with style sheets before) I thought Id do a How....
manifest.json
{
"name": "Get all css rules in stylesheets",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js" : ["myscript.js"],
"run_at":"document_end"
}
],
"permissions": [
"tabs", "<all_urls>"
],
"version":"1.0"
}
myscript.js
// Create the div we use for communication
var comDiv = document.createElement('div');
comDiv.setAttribute("id", "myCustomEventDiv");
document.body.appendChild(comDiv);
// Utitlity function to insert some js into the page, execute it and then remove it
function exec(fn) {
var script = document.createElement('script');
script.setAttribute("type", "application/javascript");
script.textContent = '(' + fn + ')();';
document.body.appendChild(script); // run the script
document.body.removeChild(script); // clean up
}
// function that gets inserted into the page
// iterates through all style sheets and collects their rules
// then sticks them in the comDiv and dispatchs the event that the content script listens for
getCSS=function (){
var rules = '';
// Create the event that the content script listens for
var customEvent = document.createEvent('Event');
customEvent.initEvent('myCustomEvent', true, true);
var hiddenDiv = document.getElementById('myCustomEventDiv');
var rules ='';
var allSheets = document.styleSheets;
for (var i = 0; i < allSheets.length; ++i) {
var sheet = allSheets[i];
for (var z = 0; z <= sheet.cssRules.length-1; z++) {
rules = rules +'\n'+ sheet.cssRules[z].cssText;
}
}
hiddenDiv.innerText = rules;
hiddenDiv.dispatchEvent(customEvent);
}
// puts the rules back in the page in a style sheet that the content script can iterate through
// youd probably do most of this in the injected script normally and pass your results back through the comDiv....Im just having fun
document.getElementById('myCustomEventDiv').addEventListener('myCustomEvent', function() {
var eventData = document.getElementById('myCustomEventDiv').innerText;
document.getElementById('myCustomEventDiv').innerText='';
var style = document.createElement('style');
style.type = 'text/css';
style.innerText=eventData;
style = document.head.appendChild(style);
var sheet = document.styleSheets[document.styleSheets.length-1];
for (var z = 0; z <= sheet.cssRules.length-1; z++) {
console.log(sheet.cssRules[z].selectorText +' {\n');
for (var y = 0; y <= sheet.cssRules[z].style.length-1; y++) {
console.log(' '+sheet.cssRules[z].style[y] + ' : ' + sheet.cssRules[z].style.getPropertyValue(sheet.cssRules[z].style[y])+';\n');
};
console.log('}\n');
};
// Clean up
document.head.removeChild(style);
document.body.removeChild(document.getElementById('myCustomEventDiv'));
});
exec(getCSS);
In the case of this question Id prolly do most of the checks in the injected script and then pass the results back through the div and its event. But I wanted to see if I could use the dom methods in the content script to go through the css and this was the only way I could figure to do it. I dont like the idea of inserting the rules back into the page, but couldnt figure any other way of doing it.
Just a guess, but since chrome extensions are Javascript based, they may have cross domain issues. Chrome sets the rules and cssRules to null when programmatically trying to get a stylesheet from another domain.
For getting all external css and all internal css file, you can use devtools API. If you want to use it in chrome extension you need to hook devtool into you chrome extension. This code will work
chrome.devtools.panels.create(
'my chrome extension',
'icon.png',
'index.html',
function(panel) {
var initial_resources = {};
// collect our current resources
chrome.devtools.inspectedWindow.getResources(function(resources) {
for (var i = 0, c = resources.length; i < c; i++) {
if (resources[i].type == 'stylesheet') {
// use a self invoking function here to make sure the correct
// instance of `resource` is used in the callback
(function(resource) {
resource.getContent(function(content, encoding) {
initial_resources[resource.url] = content;
});
})(resources[i]);
}
}
});
}
);
Answer is late, but I think I can help. One method of accessing the cssRules of external sheets protected by CORs is to use Yahoo's YQL service. I've incorporated it into a developer tools extension for Chrome for capturing styles and markup for a page fragment. The extension is in the Chrome Web Store and is on Github.
Grab the source from Github and look at the content.js script to see how YQL is used. Basically, you'll make an AJAX call to YQL and it will fetch the CSS for you. You'll need to take the CSS content and either inject it into the page as an embedded style tag or parse the CSS using JavaScript (there are some libraries for that purpose). If you choose to inject them back into the document, make sure to set the new style blocks to disabled so that you don't screw up the rendering of the page.
The extension itself might be useful to you:
what's the best approach to change the background of my website at each visit ?
1) write php code, loading a random css file containing the background property
2) write php code, generating different html (and including the background property directly into html code
3) something else ?
thanks
This can be done in your theme's page.tpl.php variable preprocessor. Store the random style in the $_SESSION array to re-use for all pages in the same user session. And append the markup to the $head variable used in the template.
YOURTHEME_preprocess_page(&$variables) {
$style = $_SESSION['YOURTHEME_background_style'];
if (!$style) {
$style = array();
//Generate your random CSS here
$style = "background-image: url('bg-". rand(0,10) .".png')";
$_SESSION['YOURTHEME_background_style'] = $style;
}
$variables['head'] .= '<style type="text/css">body {'. implode("\n", $style) .'}</style>';
}
Usually, $head is placed before $style in the page.tpl.php templaye, so CSS rules from any .css files will overrides your random rule. You may have to use !important in your random CSS to avoid this.
I would probably:
Use hook_user op login to detect the login and then store the background color code in the user object.
In your page template create an inline style for the background color that uses the value stored on the user object. For anonymous users don't do anything and have default defined in a style sheet.
Use a session cookie. Could be set either via js (client side) or something like php (server-side). Here's an example of a js-only solution:
<!doctype html>
<html><head><script>
var backgrounds=['foo.png', 'bar.png', 'hahah.png'];
function setBg () {
var currentBg=readCookie('which_bg');
if (!currentBg) {
currentBg=backgrounds[Math.random()*backgrounds.length|0];
createCookie('which_bg', currentBg);
}
document.body.style.backgroundImage='url('+currentBg+')';
}
// from http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
</script></head>
<body onload="setBg();">
...
</body></html>
To change the background image at each page load (not exactly "visit" though), you can use the Drupal module Dynamic Background. For Drupal 7, only the 7.x-2.x branch contains the option for cycling backgrounds randomly. You would install it with:
drush dl dynamic_background-7.x-2.x && drush en dynamic_background
The feature can also be added to the 7.x-1.x branch with a patch, and to the 6.x-1.x branch similarly.