I want to take print out of a webpage. I have written code for this and this work.The code is:
function printPage(){
var tableData = '<table border="1">'+document.getElementsByTagName('table')[0].innerHTML+'</table>';
var data = '<button onclick="window.print()">Print this page</button><br/>'+tableData;
myWindow=window.open('','','width=500,height=600');
myWindow.innerWidth = screen.width;
myWindow.innerHeight = screen.height;
myWindow.screenX = 0;
myWindow.screenY = 0;
myWindow.document.write(data);
myWindow.focus();
};
But I don't want 'Print this page' button in print out.
You can use the #media css style method:
#media print {
/* css here to take out the "print this */
}
This will only apply the css styles when you print.
For example, you can give your button a class, say class="printbtn"
then:
#media print {
.printbtn { display: none; }
}
Simply use css for print defined area as....
<style type="text/css">
#printit { display: block; }
#media print
{
#dont-printit { display: none; }
#printit { display: block; }
}
</style>
and use <div id="printit"> to print the part of web area......
Related
I am trying to create a random background image picker. What I have works, but it seems clunky and redundant. Can I get help in figuring out a better way to write this?
Requirements:
Random background for page should be displayed each time the page is
refreshed.
Each background has a specific blurb of text that goes with it, so
the correct text needs to be displayed with each background.
Have a list of links to show the other backgrounds/text
Currently-displaying background/text should not be listed in the
index.
Example: if background3.jpg is displaying, the list should only have background1.jpg, background2.jpg, and background4.jpg.
PHP
$backgrounds =
array(
'cat1.jpg', 'cat2.jpg', 'cat3.jpg', 'cat4.jpg', 'cat5.jpg', 'cat6.jpg'); // array of image files
$randBg = rand(0, count($backgrounds)-1); // generate random number size of the array
$selectedBg = "$backgrounds[$randBg]"; // set variable equal to which random filename was chosen
$strings = array('This kitten has a filter', 'This cat is in the dark', 'This kitten has green eyes', 'This cat has a mask', 'This is Grumpy Cat', 'This cat is orange'); // array of strings, that correspond to each image
function showString($backgrounds, $randBg, $strings) {
for ($b = 0; $b < count($backgrounds); $b++) {
if ($b == $randBg) {
echo $strings[$b]; // Loop through the image array and print corresponding text from strings array
}
}
}
HTML
<div id="text">
<h1><?php showString($backgrounds, $randBg, $strings); ?></h1>
</div>
<div id="index">
<ul>
<li id="1">Filter</li>
<li id="2">The dark</li>
<li id="3">Green eyes</li>
<li id="4">Mask</li>
<li id="5">Grumpy</li>
<li id="6">Orange</li>
</ul>
</div>
CSS
body {
/* randomly selected background image */
background-image: url(images/<?php echo $selectedBg; ?>);
background-size: cover;
background-repeat: no-repeat;
}
div#text { /* the text from the respective background image goes in this div */
background-color: rgba(255, 255, 255, 0.8);
width: 50%;
margin: 10% auto 0 auto;
display: block;
text-align: center;
padding: 25px;
}
div#text h1 {
color: #000;
}
div#index { /* use this menu to view other background images */
background-color: rgba(255, 255, 255, 0.8);
width: 50%;
position: absolute;
margin-left: auto;
margin-right: auto;
bottom: 0;
}
div#index ul {
list-style-type: none;
overflow: hidden;
}
div#index ul li {
float: left;
padding: 25px;
}
div#index ul li:hover {
background-color: #000;
color: #fff;
cursor: pointer;
}
jQuery
var selected = $("li"); // make var for the list items
var bgsArray = [1, 2, 3, 4, 5, 6]; // make array of backgrounds
var strings = [ // make array of strings
"This kitten has a filter",
"This cat is in the dark",
"This kitten has green eyes",
"This cat has a mask",
"This is Grumpy Cat",
"This cat is orange"
];
var current = bgsArray[Math.floor(Math.random() * bgsArray.length)]; // get a background image randomly (can't be anything else or else the initial image is always the same on reload).
if ($("body").css("background-image", "url('images/cat" + current + ".jpg')")) { // check current background image against the random number
$("div#text h1").html("" + strings[current - 1]); // make sure correct text displays
$("li#" + current).css("display", "none"); // hide current displaying bg in index
$("li#" + current).siblings().css("display", "block"); // make sure all other index values are showing
}
$.each(selected, function() { // function to iterate through all list items
selected.click( function() { // function for clicking on list item
var li_id = $(this).prop("id"); // get the id of the <li> that was just clicked
var cssBg = "url('images/cat" + li_id + ".jpg')"; // create string for bg url with id
$("body").css("background-image", cssBg); // change page bg to new image with corresponding id
$("div#text h1").html("" + strings[li_id - 1]); // change the text
if ($("body").css("background-image", cssBg)) { // hide the <li> for the bg that's currently displaying, but show all others
$("li#" + li_id).css("display", "none");
$("li#" + li_id).siblings().css("display", "block");
}
});
});
My goal is to learn how to conceptualize refactoring this (if that makes sense), because I know there is a much neater way to write it. Are both PHP and jQuery even required? Should I be using AJAX? I used jQuery to minimize HTTP requests after the initial pageload. If it's more efficient to use one language, I'd rather go that way. Thank you for any and all assistance.
Not entirely sure from your description, but it seems you don't need php. You can just show a random image using JS alone. Also, it is cleaner to use a map to connect the image to the blurb of text.
E.g.:
var imageToText = {
"imageNameA": "cat text A",
"imageNameB": "cat text B",
...
}
flow: Based on size of map, fetch imageName + corresponding text
Also, talking about the event handlers a bit
You have:
var selected = $("li"); // make var for the list items
...
$.each(selected, function() { // function to iterate through all list items
selected.click( function() { // function for clicking on list item
...
})
})
This can be refactored to:
$("li").click(function(){
var $el = $(this);
//do something...
})
hth
If you know the key of the element in the array - you don't need to loop over the keys to get the value, you can just get the value:
function showString($backgrounds, $randBg, $strings) {
echo $strings[$randBg]; // Loop through the image array and print corresponding text from strings array
}
The function mt_rand is better than rand.
$randBg = mt_rand(0, count($backgrounds)-1);
If you want to get a random element from an array you can use the array_rand function:
$key = array_rand($backgrounds);
$backgrounds[$key]; // this is the random-background you want
$h1 = $strings[$randBg];//will return correct string for the BG
I am trying to get a random background image to load on my wordpress site home page every time the page is loaded or refreshed. Here is the code I have so far:
This is the code I have in my style sheet.
style.css
body.home {
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
height: 100%;
width: 100%;}
This is the code I have on my home.php file.
home.php
<script>
var randomImage = {
paths: [
"images/home-bg/website-background1.jpg",
"images/home-bg/website-background2.jpg",
"images/home-bg/website-background3.jpg",
"images/home-bg/website-background4.jpg",
"images/home-bg/website-background5.jpg",
"images/home-bg/website-background6.jpg",
"images/home-bg/website-background7.jpg",
],
generate: function(){
var path = randomImage.paths[Math.floor(Math.random()*randomImage.paths.length)];
var img = new Image();
img.src = path;
$("body.home").html(img);
$("body.home").attr("href", path);
}
}
randomImage.generate();
</script>
If you would like to check out the website its http://americasfinestlighting.com/
Thanks,
William
Just change body background like below:
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<body>
</body>
<script>
var randomImage = {
paths: [
"https://www.ricoh.com/r_dc/caplio/r7/img/sample_04.jpg",
"http://www.riscon.co.uk/wp-content/uploads/2015/08/sample3.jpg",
"http://cdn6.fonearena.com/i/SonyXperiaZ2CameraSamples/sony-xperia-z2-camera-sample-macro-6.jpg",
"https://cdn.photographylife.com/wp-content/uploads/2012/10/Nikon-D600-Sample-4.jpg",
],
generate: function(){
var path = randomImage.paths[Math.floor(Math.random()*randomImage.paths.length)];
$('body').css('background', 'url('+path+') no-repeat');
}
}
randomImage.generate();
</script>
DEMO
I was able to accomplish this by adding a snip-it of php to my functions.php file.
add_filter('body_class','random_background_images');
function random_background_images($classes) {
// Generate Random number from 1 to 7.
$background_class = 'background_' . rand(1,7);
$classes[] = $background_class;
return $classes;
}
Then I changed my CSS to the following:
body.home.background_1 {
background-image: url("images/home-bg/website-background1.jpg");
}
body.home.background_2 {
background-image: url("images/home-bg/website-background2.jpg");
}
body.home.background_3 {
background-image: url("images/home-bg/website-background3.jpg");
}
body.home.background_4 {
background-image: url("images/home-bg/website-background4.jpg");
}
body.home.background_5 {
background-image: url("images/home-bg/website-background5.jpg");
}
body.home.background_6 {
background-image: url("images/home-bg/website-background6.jpg");
}
body.home.background_7 {
background-image: url("images/home-bg/website-background7.jpg");
}
If you want the background to change on all pages not just the home page remove the .home from the CSS Example:
body.background_1 {
background-image: url("images/home-bg/website-background1.jpg");
}
Hope this helps anyone else who is looking :-)
Wrap the randomImage Object and the randomImage.generate invocation, inside jQuery .ready() method to execute when the DOM is fully loaded.
Also space out ".home" from "body" this queries for "home class" in body
<script>
$( document ).ready(function() {
var randomImage = {
paths: [
"images/home-bg/website-background1.jpg",
"images/home-bg/website-background2.jpg",
"images/home-bg/website-background3.jpg",
"images/home-bg/website-background4.jpg",
"images/home-bg/website-background5.jpg",
"images/home-bg/website-background6.jpg",
"images/home-bg/website-background7.jpg",
],
generate: function(){
var path = randomImage.paths[Math.floor(Math.random()*randomImage.paths.length)];
var img = $('<img id="img-responsive">'); // This is Equivalent to $(document.createElement('img'))
img.attr('src', path);
img.appendTo('#imagediv'); // The div ID you want to append to
}
}
randomImage.generate();
});
</script>
View on CODEPEN
Is there a way I can use a HTML form text box to perform an advanced search where I will be able to start typing a username of one of my members and it will list all members close to what I am still typing, something like the facebook search, but only with names (not profile pictures).
So for example, if I had a member list with contents like:
Jamie123
Jackzo
Josh
Dan
When I typed in my box, "J" all of the above apart from "Dan" would show in a drop box.
When I typed in my box, "Ja", "Dan" and "Josh" would not show... and so on?
Is this possible ? If so, How can i do this ?
I would look into using Select2. You can find out more here: http://ivaynberg.github.io/select2/
Yes...lets start by creating your text box:
<input type="text" name="DEMO_NAME" id="DEMO_NAME" alt="Possible Results" onKeyUp="searchSuggest();" autocomplete="off">
You will need a div sto show your results while the user is typing (place it under the textbox via css):
<div id="search_suggest"></div>
On the top of the html page you will have to include (apart from jquery) a .js file which will handle the request:
<script language="JavaScript" type="text/javascript" src="ajax_search.js" charset="utf-8"></script>
aja_search.js code is:
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Please update your Browser");
}
}
//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();
//Called from keyup on the search textbox.
//Starts the AJAX request.
function searchSuggest() {
if (searchReq.readyState == 4 || searchReq.readyState == 0) {
var str = encodeURI(document.getElementById('DEMO_NAME').value);
searchReq.open("GET", 'search.php?search=' + str, true);
searchReq.onreadystatechange = handleSearchSuggest;
searchReq.send(null);
}
}
//Called when the AJAX response is returned.
function handleSearchSuggest() {
if (searchReq.readyState == 4) {
var ss = document.getElementById('search_suggest')
ss.innerHTML = '';
if(document.getElementById('DEMO_NAME').value.length > 2)
{
var str = searchReq.responseText.split("\n");
for(i=0; i < str.length - 1; i++) {
//Build our element string. This is cleaner using the DOM, but
//IE doesn't support dynamically added attributes.
var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
suggest += 'onmouseout="javascript:suggestOut(this);" ';
suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
suggest += 'class="suggest_link">' + str[i] + '</div>';
ss.innerHTML += suggest;
}
}
else
{
ss.innerHTML = 'Please insert at least 3 characters';
}
}
}
//Mouse over function
function suggestOver(div_value) {
div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
div_value.className = 'suggest_link';
}
//Click function
function setSearch(value) {
document.getElementById('DEMO_NAME').value = value;
document.getElementById('search_suggest').innerHTML = '';
}
as you can see from the js above, user must input at least 3 characters in order to fire up the search. I strongly advise you to keep it.
last but not least you need the search.php file which is called by ajax in order to fetch results:
$search = $_GET["search"];
if(!empty($search))
{
$query = mysql_query("SELECT * FROM your_table WHERE username like('%" . simple_protect($search) . "%') ORDER BY username") or die (mysql_error());
while ($row = mysql_fetch_assoc($query))
{ //echo $query;
echo strip_all($row['username'])."\n";
}
}
else
{
echo "No Records available";
}
simple_protect and strip_all are functions of mine, the first one sanitizes the input while the second removes slashes etc. You can use your own.
finally you will need the css that shows results correctl, mine looks like this:
.suggest_link {
background-color: #333333;
padding:2px 4px 4px 2px;
color:#858585; font-family:Verdana; font-size:11px; color:#ffffff;
}
.suggest_link_over {
background-color: #666666;
padding:2px 4px 4px 2px;
color:#858585; font-family:Verdana; font-size:11px; color:#ffffff;
}
#search_suggest {
background-color: #333333;
text-align: left;
z-index:20;
width:240px; height: inherit;
border:hidden;
color:#ffffff; font-family:Verdana; font-size:11px; cursor: pointer;
}
and voila! you have your advanced search...
You have to use javascript for this, i recommend JQuery. You can do this with a built in function in JQuery called ajax, with it you can send a POST request to the server without refreshing the page. And then use php to fetch the data.
I recommend going to youtube and look at some tutorials if you ar new to javascript, look for JQuery tutorials.
I have the following problem.
I have a register which is on the right side of the page. It has a button at the end and if you click on the button the register should toogle to the screen and if you click again, it should be hidden again.
This is my current solution:
jsfiddle.net/6JLr9/
(Button: green, Content: red
My problem here is: During the hiding and showing animation, the button doesn't move, when the animation is finished, the button is directly moved to the new (correct) position. How can I make the button move at the same time?
Thank you in advance
I have made some change in Javascript and CSS. Here are the changes
Javascript :
$(document).ready(
function(){
$('.videohilfe').click(function(){
if($('.videohilfe-wrapper').css('right') == '-200px')
$('.videohilfe-wrapper').animate({right:'0px'});
else
$('.videohilfe-wrapper').animate({right:'-200px'});
});
}
);
CSS :
.registers-wrapper {
position:fixed;
right:-200px; /* changed */
z-index:50;
}
I've updated your jsfiddle.
Changed a few things in js and css.
JS:
$(document).ready(
function(){
$('.registers').click(
function(){
if($(this).hasClass('open')){
$('.registers-wrapper').animate({'margin-left':'-33px'},1000);
$(this).removeClass('open');
}else{
$('.registers-wrapper').animate({'margin-left':'-233px'},1000);
$(this).addClass('open');
}
})
}
);
CSS:
.registers {
width:33px;
height:136px;
background-repeat:no-repeat;
float:left;
z-index:50;
}
.registers-content {
height:136px;
width:200px;
background-repeat:repeat-x;
background-color:red;
float:left;
z-index:50;
}
.registers-wrapper {
position:fixed;
left:100%;
z-index:50;
margin-left:-33px;
width:233px;
}
.videohilfe-wrapper {
top:160px;
}
.videohilfe {
background-color:green;
}
.videohilfe-content {
}
Now it works as expected.
Is there a way that I can change a css style sheet's data from a html form and php and/or JQuery. So if I have the following
widths.css
#main #section1 {
width: 25%;
}
#main #section2 {
width: 50%;
}
#main #section3 {
width: 25%;
}
So I want to have 3 text boxes S1, S2 and S3 and then a user can place values into each text box. It will check they add up to 100% or less and then it will write them to the css in place of 25%, 50% and 25%. How would I achieve this using php and/or JQuery.
Thanks
well there is a dirty but solution to this. use php to write javascript to the the html possibly after ending of body tag.
so the code goes like this
..
...
</body>
<?php echo <<< code
<script type="text/javascript">
document.getElementById("section1").style.width="$_POST['s1']";
// and then for each section u can do this
code;
?>
you will have to set the CSS dynamically on the page it self. Once the user entered the data, you can use little bit of AJAX to change the styles. So something like below would be your PHP and styles on the page. if you want this to be a permenant change make sure to put the settings in a DB against the user's profile. This can be added to your AJAX script as well.
<style type="text/css">
#main #section1 {
width: <?php echo $s1; ?>%;
}
#main #section2 {
width: <?php echo $s2; ?>%;
}
#main #section3 {
width: <?php echo $s3; ?>%;
}
</style>
HTH
You can use the jQuery addClass() to add a specific CSS class with the style you require.
To use PHP, you could use CSS internally on the page:
<style type="text/css">
<?php echo "width: 100px;" //for example ?>
</style>
But I wouldn't necessarily recommend that.
something basic but which should work
$(".validate").click(function(){
//I've assumed your text inputs were children of an element with id section$i
var w1 = Number($("#section1 input").val());
var w2 = Number($("#section2 input").val());
var w3 = Number($("#section3 input").val());
if(w1+w2+w3 == 100){
//here you change css rules for #section$i elements
$("#section1").css("width",w1+"%")
$("#section2").css("width",w2+"%")
$("#section3").css("width",w3+"%")
}
else{
alert("sum of values must equals 100%")
}
});
assuming that you have a clickable area with class validate
You can use this script i just made for you:
var merge = function(objectCollections){
var array = new Array();
foreach(objectCollections,function(objectCollection){
foreach(objectCollection,function(object){
array.push(object);
});
});
return array;
}
var foreach = function(object,loop){
for (var key in object) {
if (object.hasOwnProperty(key)) {
loop(object[key],key);
}
}
}
var changeCSS =function(value){
var links = document.getElementsByTagName('link');
var styles = document.getElementsByTagName('style');
var sheets = merge([links,styles]);
var rules = value.split(/[(\ *{)(\})]/g);
for(var i in sheets){
if(typeof sheets[i] == 'object'){
var sheet = sheets[i].sheet ? sheets[i].sheet : sheets[i].styleSheet;
for(var j in sheet.cssRules){
if(typeof sheet.cssRules[j].selectorText != 'undefined'){
if(sheet.cssRules[j].selectorText == rules[0]){
sheet.cssRules[j].cssText = value;
console.debug(sheet.cssRules[j].cssText);
}
}
}
}
}
}
usage example:
changeCSS('#main #section1 {width: 25%;}');
this will change the css (not set a style on a tag or something)