I have a form that requires printing. However, there might be fields that will be left blank and I would like them to be excluded from my print view altogether. I am talking about the JavaScript window.print(); function and the print window that it opens.
Is there a way I can do something like this? Is there a way for me to handle logic in such events (ie. before print?).
You could use CSS #media combined with some javascript to change the class dependent on whether the field is empty or not. Something like this...
var fields = document.getElementsByClassName("field");
for(var i=0; i < fields.length; i++){
fields[i].addEventListener('keyup', function() {
if(this.value.length) {
this.parentElement.className = "";
} else {
this.parentElement.className = "empty";
}
});
}
#media print {
.empty {
display: none;
}
}
<div class="empty">Name: <input class="field"></div>
<div class="empty">Field: <input class="field"></div>
<div class="empty">Foo: <input class="field"></div>
(In the snippet, add something to a field but not all and then hit ctrl+p. you wont see the empty fields in the print preview)
If using jQuery you could cleanup the selectors and looping making the js something like this
$(".field").on("keyup", function () {
$this = $(this);
if ($this.val().length) {
$this.parent().removeClass("empty");
} else {
$this.parent().addClass("empty");
}
});
You can watch for the window.print event and use some jquery or javascript to check for empty inputs and hide them.
(function() {
var beforePrint = function() {
$('input').each(function(i,el){
if($(el).val() == ''){
$(el).hide();
}
});
};
var afterPrint = function() {
$('input').show();
};
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function(mql) {
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;
}());
https://jsbin.com/gacikezulo/edit?html,js,console,output
Read this article here. But I took the combined script which should work in everything except Opera
Related
Let's say we have a div with id = '123'
Ho to make it invisible with js without affecting its html code?
So document.getElementById('123').style.display = 'none' is not an option.
JS only
UPD:
I just have interesting task! I have to hide some comments with js from guestbook , but when I change html code to hide it, Server somehow understands what I've done and redirects me to warning Page. So I have to do something with that.
UPD2:
I had obfuscated script on my page
function check_divs() {
var try_again = true;
var arr_divs = document.getElementById('content').getElementsByTagName('div');
if (arr_divs.length != divs_count) {
try_again = false;
} else {
for (var i = 0; i < arr_divs.length; i++) {
if ((arr_divs[i].style.display == 'none') || (arr_divs[i].style.position == 'absolute')) {
try_again = false;
};
};
}; if (try_again) {
setTimeout(check_divs, 998);
} else {
document.location.href = '/alert.html';
};
}
This one, so my solution was to clear all timeouts.
document.getElementById('123').style.visibility = 'hidden';
or
document.getElementById('123').setAttribute('style','display:none');
or
document.getElementById('123').setAttribute('style','visibility:hidden');
or if you have jQuery libraries
$('#123').css('visibility','hidden')
or
$('#123').css('display','none')
Any of that help?
I currently have the following code on my website:
$(document).ready(function() {
$("#contact").on("click", function(e)
{
e.preventDefault();
$("#contactform").toggle('fast');
});
});
I would like to have an if(isset($_GET['email')); trigger this function as well, so have it open on page load if the $_GET variable is set.
I'm rather new with Jquery and not sure if this is possible, I also have another somewhat related question, I'm not sure if I should make a new question for this as I'm fairly new to stackoverflow as well, but here it is.
Say I have two of these:
$(document).ready(function() {
$("#contact").on("click", function(e)
{
e.preventDefault();
$("#contactform").toggle('fast');
});
});
$(document).ready(function() {
$("#archivestop").on("click", function(e)
{
e.preventDefault();
$("#archives").toggle('fast');
});
});
I want one to close if the other one is opened, how would I go about this?
Thanks!
Here's the Javascript-solution:
function getParam(key) {
var paramsStr = window.location.search.substr(1, window.location.search.length),
paramsArr = paramsStr.split("&"),
items = [];
for (var i = 0; i < paramsArr.length; i++) {
items[paramsArr[i].split("=")[0]] = paramsArr[i].split("=")[1];
}
if (key != "" && key != undefined) {
// return single
if (items[key] != undefined) {
return items[key];
} else {
return null;
}
} else {
// return all (array)
return items;
}
};
if (getParam("email")) {
// ...
}
Regarding your second question you can use the following to determine if an element is visible:
var bool = $('.foo').is(":visible");
So to hide an element if it is visible you would do something like this:
if ($('.foo').is(":visible")) {
$('.foo').hide();
}
I'm silly and have answered my first question. I still have yet to have my coffee.
The following works, just insert it into the div that is to be displayed:
<div id="contactform" style="<?php if(isset($_POST['email'])) echo "display:block;" ?>">
content
</div>
Add multiple items to text-area with duplicate items.
I have one text-area which store data after clicked add data link.
How can i prevent add duplicate items to text-area?
JavaScript call DOM event:
var Dom = {
get: function(el) {
if (typeof el === 'string') {
return document.getElementById(el);
} else {
return el;
}
},
add: function(el, dest) {
var el = this.get(el);
var dest = this.get(dest);
dest.appendChild(el);
},
remove: function(el) {
var el = this.get(el);
el.parentNode.removeChild(el);
}
};
var Event = {
add: function() {
if (window.addEventListener) {
return function(el, type, fn) {
Dom.get(el).addEventListener(type, fn, false);
};
} else if (window.attachEvent) {
return function(el, type, fn) {
var f = function() {
fn.call(Dom.get(el), window.event);
};
Dom.get(el).attachEvent('on' + type, f);
};
}
}()
};
JQuery add data to textarea:
$("#lkaddlanguage").click(function(){
var totalstring;
var checkconstring = $("#contentlng").text();
var strLen = checkconstring.length;
myStr = checkconstring.slice(0,strLen-1);
//alert(myStr);
var checkedItemsArray = myStr.split(";");
var j = 0;
var checkdup=0;
totalstring=escape($("#textval").val()) ;
var i = 0;
var el = document.createElement('b');
el.innerHTML = totalstring +";";
Dom.add(el, 'txtdisplayval');
Event.add(el, 'click', function(e) {
Dom.remove(this);
});
});
HTML Display data
<input type="textbox" id="textval">
<a href="#lnk" id="lkaddlanguage" >Add Data</a>
<textarea readonly id="txtdisplayval" ></textarea>
This seems a very straightforward requirement to me, so I'm not quite clear where you're getting stuck. I have not tried too hard to figure out your existing code given that you are referencing elements not shown in your html ("contentlng"). Also, mixing your own DOM code with jQuery seems a bit pointless. You don't need jQuery at all, but having chosen to include it why then deliberate not use it?
Anyway, the following short function will keep a list of current items (using a JS object) and check each new item against that list. Double-clicking an item will remove it. I've put this in a document ready, but you can manage that as you see fit:
<script>
$(document).ready(function() {
var items = {};
$("#lkaddlanguage").click(function(){
var currentItem = $("#textval").val();
if (currentItem === "") {
alert("Please enter a value.");
} else if (items[currentItem]) {
alert("Value already exists.");
} else {
items[currentItem] = true;
$("#txtdisplayval").append("<span>" + currentItem + "; </span>");
}
// optionally set up for entry of next value:
$("#textval").val("").focus();
return false;
});
$("#txtdisplayval").on("dblclick", "span", function() {
delete items[this.innerHTML.split(";")[0]];
$(this).remove();
});
});
</script>
<input type="textbox" id="textval">
<a href="#lnk" id="lkaddlanguage" >Add Data</a><br>
<div id="txtdisplayval" ></div>
<style>
#txtdisplayval {
margin-top: 5px;
width : 200px;
height : 100px;
overflow-y : auto;
border : 1px solid black;
}
</style>
Note I'm using a div (styled to have a border and allow vertical scrolling) instead of a textarea.
As you can see I've coded it to display an alert for duplicate or empty items, but obviously you could remove that and just ignore duplicates (or substitute your own error handling). Also I thought it might be handy to clear the entry field and set focus back to it ready for entry of the next value, but of course you can remove that too.
Working demo: http://jsfiddle.net/LTsBR/1/
I'm confused.
The only variable that might have duplicates comes from:
var checkedItemsArray = myStr.split(";");
However, checkedItemsArray is not used for anything.
Incidentally, the escape method is deprecated in favour of encodeURIComopnent.
When setting the value of the textarea, do just that: assign to its value property, not to its innerHTML (it can't have markup inside it or any elements, only text nodes).
If you want to check that the members of checkedItemsArray are unique, and you don't mind if they are sorted, you can use a simple function like:
function unique(arr) {
arr.sort();
var i = arr.length;
while (i--) {
if (arr[i] == arr[i - 1]) {
arr.splice(i, 1);
}
}
return arr;
}
Orignal order can be maintained, but it's a bit more code.
I'm creating a simple jQuery editor, nothing complicated, and just can't seem to find out why the events do not work. See code below.
var $editor = $('<div>').addClass('editor')
.insertBefore(this.$element)
.append(this.$element);
var $b = $('<div>').addClass('button-wrapper')
.appendTo($editor);
this.$element.css({height:this.opts.height,width:this.opts.width});
//Load up each button.
$.each(this.opts.buttons.split(' '), function(i, button)
{
//If its an empty string keep going.
if(button == '')return true;
//Generate a button.
$('<div>').data('buttonName', button)
.addClass(button.toLowerCase())
.click(clicked)
.hover(hover, hover)
.appendTo($b);
});
To go over it, simply, $element represents the textarea that I am using as the base element, $b represents the button wrapper, and $editor is the div to wrap around all of these things. When I append the buttons to $editor none of the events fire, however, when I append to document.body it works perfectly fine. For the record, the event clicked and hover are nothing special, just testers to see if the events are working.
I guess the issue is actually at all places you are using <div> but it should be just div
like below -
var $editor = $('div').addClass('editor')
.insertBefore(this.$element)
.append(this.$element);
I've rewritten your code a little bit, just to figure out what you're doing. This seems to work for me, unless I didn't understand what the problem is that you're describing. The buttons react to hover as well as click events. Aside from writing the things you're doing differently, there's no substantial change in the code.
I suppose there's a chance that Val was right in that there may be other elements overlaying your buttons. You haven't shown us your CSS, so it's hard to tell what's going on on your side.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style>
.bold, .italic, .underline{ width: 50px; height: 20px; background: green; margin: 10px; }
</style>
</head>
<body>
<textarea class="demo">
</textarea>
<script type="text/javascript">
jQuery(
function($)
{
(function($){
//Constructor to make a new editor.
function TEditor(element, opts)
{
//Load in the element.
this.$element = $(element);
this.opts = opts;
//Let the browser know the object is ready.
this.enabled = true;
}
//The actual editor class.
TEditor.prototype = {
display: function()
{
var
$editor = this.$element.wrap('<div class="editor" />').parent(),
$b = $('<div class="button-wrapper" />').appendTo($editor);
this.$element.css({height:this.opts.height,width:this.opts.width});
//Load up each button.
$.each(this.opts.buttons.split(' '), function(i, button)
{
//If its an empty string keep going.
if(button == '') return true;
//Generate a button.
$('<div class="' + button.toLowerCase() + '" />')
.data('buttonName', button)
.appendTo($b)
.click(clicked)
.hover(hover, hover);
});
},
enable: function()
{
this.enabled = true;
},
disable: function()
{
this.enabled = false;
},
validate: function()
{
if(!this.$element[0].parentNode)
{
this.destroy();
this.$element = null;
this.options = null;
}
}
}
//JQuery function extension.
$.fn.teditor = function(options)
{
options = $.extend({}, $.fn.teditor.defaults, options);
//On load create a new editor.
function get(ele)
{
var editor = $.data(ele, 'editor');
if(!editor)
{
editor = new TEditor(ele, options);
editor.display();
$.data(ele, 'editor', editor);
}
return editor;
}
//Initialize.
this.each(function(){get(this);})
return this;
};
$.fn.teditor.defaults = {
buttons: 'Bold Italic Underline',
height: '150px',
width: '500px'
};
function clicked(e)
{
alert(e);
}
function hover(e)
{
console.log('hover');
}
})(jQuery);
$('.demo').teditor();
}
);
</script>
</body>
</html>
I have the following code in a jQuery JavaScript document running on a page (THIS IS CURRENT):
$(window).resize(function(){
detectscreen();
});
function windowWidth() {
if(!window.innerWidth) {
// user is being a git, using ie
return document.documentElement.clientWidth;
} else {
return window.innerWidth;
}}
gearsExists = false;
function detectscreen() {
shouldExist = windowWidth() >= 1300;
if (shouldExist != gearsExists) {
if (shouldExist) {
$('body').append('<div id="gearsfloat"></div>');
$('#clickGoTop').fadeTo(0,0);
$('#clickGoTop').hover(function() {
$(this).stop().fadeTo(500,1);
}, function() {
$(this).stop().fadeTo(500,0);
});
} else {
$('#gearsfloat').remove();
$('#clickGoTop').remove();
}
gearsExists = shouldExist;
}
}
This code is from my previous question, branched here simply because I think it is related.
The problem here is that the beginning is fine: it is displayed. However, if the screen is resized to less than 1300, it disappears; still good.
Now I make the window again larger than 1300. Suddenly the gear element is doubled. Another screen squish and largen and BAM, there's three now. Do this several times and it quickly adds up.
How can I stop this?
If you hook any code in resize event, make sure that your code doesn't resize the window again. Otherwise, resize event will fire again and your code will go in infinite loop.
Also, in your code, you are not using the global gearsExists variable. Remove the 'var' at the bottom of the method to use the global variable.
function detectscreen() {
// Your original code
//var gearsExists = shouldExist; //This code will create new local variable.
gearsExists = shouldExist;
}
}
EDIT: Here's what I would do:
//We will add only one variable to the global scope.
var screenManager = function()
{
var pub = {};
var inResizeHandler = false;
pub.getWindowWidth = function()
{
return window.innerWidth || document.documentElement.clientWidth;
};
pub.manage = function()
{
//if we are already in the resize handler, don't do anything.
if(inResizeHandler)
return;
inResizeHandler = true;
if(pub.getWindowWidth() < 1300)
{
$('#gearsfloat').remove();
//You don't have to remove clickGoTop because it is part of gearsfloat.
inResizeHandler = false;
return;
}
if($('#gearsfloat').length > 0)
{
inResizeHandler = false;
return false;
}
$('body').append('<div id="gearsfloat"></div>');
$('#clickGoTop').fadeTo(0,0);
$('#clickGoTop').hover(
function() {$(this).stop().fadeTo(500,1);},
function() {$(this).stop().fadeTo(500,0);
});
inResizeHandler = false;
};
pub.init = function()
{
$(window).resize(pub.manage);
};
return pub;
}();
$(document).ready( function() { screenManager.init(); } );
EDIT:
Final working version:
http://jsbin.com/ufipu
Code:
http://jsbin.com/ufipu/edit
Haha! After a while, I decided to ignore everything said by everyone else for a while (sorry) and try to see if I could figure it out myself, and I did!
Thanks to SolutionYogi for all the help, but the code he gave me was out of my expertise; it was impossible to debug. My solution is not as pretty as his (if you can help optimize, please do), but it works:
function WinWidth() {
// check width of content
if(!window.innerWidth) {
// you git, how dare you use ie
return document.documentElement.clientWidth;
} else {
return window.innerWidth;
}
};
function gearsAction() {
if(WinWidth() >= 1300) {
$('body').append(
'<div id="gearsfloat"></div>');
$('#clickGoTop').fadeTo(0,0);
$('#clickGoTop').hover(
function() {$(this).stop().fadeTo(500,1);},
function() {$(this).stop().fadeTo(500,0);});
};
};
$(document).ready(function() {
gearsAction();
});
$(window).resize(function() {
$('#gearsfloat').remove();
gearsAction();
});