How can I change this JS to make it visible? - javascript

_createInput: function(){
var self = this;
var input = document.createElement("input");
input.setAttribute('type', 'file');
input.setAttribute('name', this._settings.name);
if(this._settings.multiple) input.setAttribute('multiple', 'multiple');
addStyles(input, {
'position' : 'absolute',
// in Opera only 'browse' button
// is clickable and it is located at
// the right side of the input
'right' : 0,
'margin' : 0,
'padding' : 0,
'fontSize' : '480px',
// in Firefox if font-family is set to
// 'inherit' the input doesn't work
'fontFamily' : 'sans-serif',
'cursor' : 'pointer'
});
var div = document.createElement("div")
div.className = 'tooltip';
div.id = 'ajaxupload-div';
div.title = 'Attach a picture';
addStyles(div, {
'display' : 'block',
'position' : 'absolute',
'overflow' : 'hidden',
'margin' : 0,
'padding' : 0,
'opacity' : 0,
// Make sure browse button is in the right side
// in Internet Explorer
'direction' : 'ltr',
//Max zIndex supported by Opera 9.0-9.2
'zIndex': 2147483583
});
// Make sure that element opacity exists.
// Otherwise use IE filter
if ( div.style.opacity !== "0") {
if (typeof(div.filters) == 'undefined'){
throw new Error('Opacity not supported by the browser');
}
div.style.filter = "alpha(opacity=0)";
}
addEvent(input, 'change', function(){
if ( ! input || input.value === ''){
return;
}
// Get filename from input, required
// as some browsers have path instead of it
var file = fileFromPath(input.value);
if (false === self._settings.onChange.call(self, file, getExt(file))){
self._clearInput();
return;
}
// Submit form when value is changed
if (self._settings.autoSubmit) {
self.submit();
}
});
addEvent(input, 'mouseover', function(){
addClass(self._button, self._settings.hoverClass);
});
addEvent(input, 'mouseout', function(){
removeClass(self._button, self._settings.hoverClass);
removeClass(self._button, self._settings.focusClass);
if (input.parentNode) {
// We use visibility instead of display to fix problem with Safari 4
// The problem is that the value of input doesn't change if it
// has display none when user selects a file
input.parentNode.style.visibility = 'hidden';
}
});
addEvent(input, 'focus', function(){
addClass(self._button, self._settings.focusClass);
});
addEvent(input, 'blur', function(){
removeClass(self._button, self._settings.focusClass);
});
div.appendChild(input);
document.body.appendChild(div);
this._input = input;
},
This JS starting at var div = document.createElement("div") produces this div tag:
<div style="display: block; position: absolute; overflow: hidden; margin: 0pt; padding: 0pt; opacity: 0; direction: ltr; z-index: 2147483583; left: 102px; top: 323.5px; width: 102px; height: 28px; visibility: hidden;">
I see where all the other attributes get changed, but how the heck can I change 'visibility: hidden;" ???
It's making me crazy please help.

Find the below section in your code i have star commented where you can modify:
addStyles(div, {
'display' : 'block', /*You cane set display none here to hide the div.*/
'position' : 'absolute',
'overflow' : 'hidden',
'margin' : 0,
'padding' : 0,
'opacity' : 0,
// Make sure browse button is in the right side
// in Internet Explorer
'direction' : 'ltr',
//Max zIndex supported by Opera 9.0-9.2
'zIndex': 2147483583,
'visibility':'hidden' /* If you don't set display none , you can set your style attribute you want to change like visibility here also */
});
Ok, to make it visible find the below code and try setting visibility there:
if (input.parentNode) {
// We use visibility instead of display to fix problem with Safari 4
// The problem is that the value of input doesn't change if it
// has display none when user selects a file
input.parentNode.style.visibility = 'hidden'; /* try setting visibility='visible' here */
}
If that doesn't work then check if any css is overriding the style property of the div by inspecting the div in your browser.

if jQuery is an option, I know there's the command $('#div').css('attribute','value');

visibility hidden is set when you "mouseout" off that input
addEvent(input, 'mouseout', function(){
removeClass(self._button, self._settings.hoverClass);
removeClass(self._button, self._settings.focusClass);
if (input.parentNode) {
// We use visibility instead of display to fix problem with Safari 4
// The problem is that the value of input doesn't change if it
// has display none when user selects a file
input.parentNode.style.visibility = 'hidden';
}
});
you can either remove that event binding or change the statement to input.parentNode.style.visibility = 'visible';

Related

add image in javascript

I'm using a WordPress plugin (open source) that will allow you to add an expandable widget for a WooCommerce product category.
This is the JS:
// mtree.js
// Requires jquery.js and velocity.js (optional but recommended).
// Copy the below function, add to your JS, and simply add a list <ul class=mtree> ... </ul>
;(function ($, window, document, undefined) {
// Only apply if mtree list exists
if($('ul.mtree').length) {
// Settings
var collapsed = true; // Start with collapsed menu (only level 1 items visible)
var close_same_level = true; // Close elements on same level when opening new node.
var duration = mtree_options.duration; // Animation duration should be tweaked according to easing.
var listAnim = true; // Animate separate list items on open/close element (velocity.js only).
var easing = mtree_options.easing_type; // Velocity.js only, defaults to 'swing' with jquery animation.
// Set initial styles
$('.mtree ul').css({'overflow':'hidden', 'height': (collapsed) ? 0 : 'auto', 'display': (collapsed) ? 'none' : 'block' });
// Get node elements, and add classes for styling
var node = $('.mtree li:has(ul)');
node.each(function(index, val) {
$(this).children(':first-child').css('cursor', 'pointer')
$(this).addClass('mtree-node mtree-' + ((collapsed) ? 'closed' : 'open'));
$(this).children('ul').addClass('mtree-level-' + ($(this).parentsUntil($('ul.mtree'), 'ul').length + 1));
});
// Set mtree-active class on list items for last opened element
$('.mtree li > *:first-child').on('click.mtree-active', function(e){
if($(this).parent().hasClass('mtree-closed')) {
$('.mtree-active').not($(this).parent()).removeClass('mtree-active');
$(this).parent().addClass('mtree-active');
} else if($(this).parent().hasClass('mtree-open')){
$(this).parent().removeClass('mtree-active');
} else {
$('.mtree-active').not($(this).parent()).removeClass('mtree-active');
$(this).parent().toggleClass('mtree-active');
}
});
// Set node click elements, preferably <a> but node links can be <span> also
node.children(':first-child').on('click.mtree', function(e){
// element vars
var el = $(this).parent().children('ul').first();
var isOpen = $(this).parent().hasClass('mtree-open');
// close other elements on same level if opening
if((close_same_level || $('.csl').hasClass('active')) && !isOpen) {
var close_items = $(this).closest('ul').children('.mtree-open').not($(this).parent()).children('ul');
// Velocity.js
if($.Velocity) {
close_items.velocity({
height: 0
}, {
duration: duration,
easing: easing,
display: 'none',
delay: 100,
complete: function(){
setNodeClass($(this).parent(), true)
}
});
// jQuery fallback
} else {
close_items.delay(100).slideToggle(duration, function(){
setNodeClass($(this).parent(), true);
});
}
}
// force auto height of element so actual height can be extracted
el.css({'height': 'auto'});
// listAnim: animate child elements when opening
if(!isOpen && $.Velocity && listAnim) el.find(' > li, li.mtree-open > ul > li').css({'opacity':0}).velocity('stop').velocity('list');
// Velocity.js animate element
if($.Velocity) {
el.velocity('stop').velocity({
//translateZ: 0, // optional hardware-acceleration is automatic on mobile
height: isOpen ? [0, el.outerHeight()] : [el.outerHeight(), 0]
},{
queue: false,
duration: duration,
easing: easing,
display: isOpen ? 'none' : 'block',
begin: setNodeClass($(this).parent(), isOpen),
complete: function(){
if(!isOpen) $(this).css('height', 'auto');
}
});
// jQuery fallback animate element
} else {
setNodeClass($(this).parent(), isOpen);
el.slideToggle(duration);
}
// We can't have nodes as links unfortunately
e.preventDefault();
});
// Function for updating node class
function setNodeClass(el, isOpen) {
if(isOpen) {
el.removeClass('mtree-open').addClass('mtree-closed');
} else {
el.removeClass('mtree-closed').addClass('mtree-open');
}
}
// List animation sequence
if($.Velocity && listAnim) {
$.Velocity.Sequences.list = function (element, options, index, size) {
$.Velocity.animate(element, {
opacity: [1,0],
translateY: [0, -(index+1)]
}, {
delay: index*(duration/size/2),
duration: duration,
easing: easing
});
};
}
// Fade in mtree after classes are added.
// Useful if you have set collapsed = true or applied styles that change the structure so the menu doesn't jump between states after the function executes.
if($('.mtree').css('opacity') == 0) {
if($.Velocity) {
$('.mtree').css('opacity', 1).children().css('opacity', 0).velocity('list');
} else {
$('.mtree').show(200);
}
}
}
}(jQuery, this, this.document));
I've added a background image using CSS and :before but the image is not clickable.
Is there a way to add it on the JS so that it can be clicked as well?
I've tried to see where to add some code but actually I'm clueless, should it be between lines 29 and 37?
You can see it in: https://tester.medicalfa.gr/test/katastima/
Ok I fixed it via css, the arrows now appears like they are clickable.
The solution is to remove the code I had added:
ul.mtree.default li.mtree-open:before {
display: inline-block;
margin-left: 200px;
background: url("../images/arrow-down.svg") no-repeat center center;
background-size: 20px 20px;
}
I removed the :before as it adds the arrow behind the text and now appears after the text as it's supposed to.
The code looks like this now:
ul.mtree.default li.mtree-open {
display: block ;
background: url("../images/arrow-down.svg") no-repeat center center;
background-size: 15px 15px;
background-position:top right;
}

How to fix the code that should highlight selected area with CSS

What I want to achieve is to make "select to inspect" type of functionality, just like the browsers have. It should only have the functionality of creating a temporary element that will be overlayed over the element that my mouse is hovering on.
I have created a screencast to show you what it should be like, and what I currently have.
Link to video on google drive
My code
function create_div(){
let style = `
background-color: rgba(130, 180, 230, 0.5);
outline: solid 1px #0F4D9A;
box-sizing: border-box;
position: absolute;
display: block;
z-index: 999999;
`
let e = document.createElement('DIV')
e.setAttribute('id', 'tester')
e.setAttribute('style', style)
document.body.appendChild( e )
}
create_div()
$( "body" ).mousemove(function( event ) {
$( '#tester' ).css({'display' : 'none'})
let target = $( event.target )
$( '#tester' ).css({'display' : 'block', "width": target.width(),
'height': target .height(), 'top' : target .offset().top,
'left' : target .offset().left});
})
This is my code written with jQuery
It creates a DIV on the page and then, on mousemove event, I set its values (height, width, and the position)
to be the same as the element that I am hovering on. But what I get is some glitchy windows when I hover over.
What am I missing here?
You need to add pointer-events: none; to the #tester's CSS - it will make DIV transparent for mouse events. It is to unglitch from mouseover-ing
To kill another possible glitch-source, let's just save somewhere last target you have processed, so it will be no need to resize/redraw #tester again.
It will result in:
function create_div(){
$("body").append(
$("<div id=\"tester\"></div>").css({
"background-color": "rgba(130, 180, 230, 0.5)",
"outline": "solid 1px #0F4D9A",
"box-sizing": "border-box",
"position": "absolute",
"display": "block",
"z-index": "999999",
"pointer-events": "none"
})
);
}
$(document).ready(create_div);
$("body").mousemove(function( event ) {
let target = $(event.target)
if (target.length === 0){
$("#tester").css({
"display" : "none"
});
$("#tester").data("target", null);
}else if(
$("#tester").data("target") === null ||
$("#tester").data("target") !== target
){
$("#tester").data("target", target);
$("#tester").css({
"display" : "block",
"width" : target.width(),
"height" : target.height(),
"top" : target.offset().top,
"left" : target.offset().left
});
}
// else {leave #tester with no changes}
});

Uncaught ReferenceError:JQuery is not defined

I am learning how to create single page apps from a book called Single Page Web Applications. I have tried the code provided just to build my first simple SPA, but when I launch it the slider isn't working and using developer tools in the browser gives the message "Uncaught ReferenceError: JQuery is not defined". Why does the error happen? The following is the code as it is written in the book. The problem is toward the bottom where I have arrows pointing.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>SPA Chapter 1 section 1.2.2</title>
<style type="text/css">
body {
width : 100%;
height : 100%;
overflow : hidden;
background-color : #777;
}
#spa {
position : absolute;
top : 8px;
left : 8px;
bottom : 8px;
right : 8px;
border-radius : 8px 8px 0 8px;
background-color : #fff;
}
.spa-slider {
position : absolute;
bottom : 0;
right : 2px;
width : 300px;
height : 16px;
cursor : pointer;
border-radius : 8px 0 0 0;
background-color : #F00;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var $ = jQuery
/*jslint browser : true, continue : true,
devel : true, indent : 2, maxerr : 50,
newcap : true, nomen : true, plusplus : true,
regexp : true, sloppy : true, vars : true,
white : true
*/
/*global jQuery */
// Module /spa/
// Provides chat slider capability
//
var spa = (function ( $ ) {
// Module scope variables
var
// Set constants
configMap = {
extended_height : 434,
extended_title : 'Click to retract',
retracted_height : 16,
retracted_title : 'Click to extend',
template_html : '<div class ="spa-slider"><\/div>'
},
// Declare all other module scope variables
$chatSlider,
toggleSlider, onClickSlider, initModule;
// DOM method /toggleSlider/
// alternates slider height
//
toggleSlider = function () {
var
slider_height = $chatSlider.height();
// extend slider if fully retracted
if ( slider_height === configMap.retracted_height ) {
$chatSlider
.animate({ height : configMap.extended_height })
.attr( 'title', configMap.extended_title );
return true;
}
// retract slider if fully extended
else if ( slider_height === configMap.extended_height ) {
$chatSlider
.animate({ height : configMap.retracted_height })
.attr( 'title', configMap.retracted_title );
return true;
}
// do not take action if slider is in transition
return false;
};
// Event handler /onClickSlider/
// receives click event and calls toggleSlider
//
onClickSlider = function ( event ) {
toggleSlider();
return false;
};
// Public method /initModule/
// sets initial state and provides feature
//
initModule = function ( $container ) {
// render HTML
$container.html( configMap.template_html );
$chatSlider = $container.find( '.spa-slider' );
// initialize slider height and title
// bind the user click event to the event handler
$chatSlider
.attr( 'title', configMap.retracted_title )
.click( onClickSlider );
return true;
};
return { initModule : initModule }; // <<<<<<<-------
}( JQuery )); // <<<<<<<--------
// Start SPA once DOM is ready
//
jQuery(document).ready(
function () { spa.initModule( jQuery('#spa') ); }
);
</script>
</head>
<body>
<div id="spa">
<div class="spa-slider"></div>
</div>
</body>
</html>
JavaScript is case sensitive. On the second line you marked with an arrow, change JQuery to jQuery (with a lowercase j):
}( jQuery ));<<<<<<<--------
Seems like the Jquery script source you're using may be outdated. Try this one:
'<script src="http://code.jquery.com/jquery-latest.min.js"></script>'

Javascript-jquery script works in chrome and firefox but not ie (cross-fade pictures)

Can someone please look at this page and figure our why it isn't looking right in Internet Explorer? It looks fine in Chrome and Firefox but in IE the layout of the photos gets messed up specifically the two photos on the right hand side of the page.
http://waldrondigitaldesigns.com/gallery.html
I am assuming it something with this script but I am no javascript or jquery expert and barely a novice
// wrap as a jQuery plugin and pass jQuery in to our anoymous function
(function ($) {
$.fn.cross = function (options) {
return this.each(function (i) {
// cache the copy of jQuery(this) - the start image
var $$ = $(this);
// get the target from the backgroundImage + regexp
var target = $$.css('backgroundImage').replace(/^url|[\(\)'"]/g, '');
// nice long chain: wrap img element in span
$$.wrap('<span style="position: relative;"></span>')
// change selector to parent - i.e. newly created span
.parent()
// prepend a new image inside the span
.prepend('<img>')
// change the selector to the newly created image
.find(':first-child')
// set the image to the target
.attr('src', target);
// the CSS styling of the start image needs to be handled
// differently for different browsers
if ($.browser.msie || $.browser.mozilla) {
$$.css({
'position' : 'absolute',
'left' : 0,
'background' : '',
'top' : this.offsetTop
});
} else if ($.browser.opera && $.browser.version < 9.5) {
// Browser sniffing is bad - however opera < 9.5 has a render bug
// so this is required to get around it we can't apply the 'top' : 0
// separately because Mozilla strips the style set originally somehow...
$$.css({
'position' : 'absolute',
'left' : 0,
'background' : '',
'top' : "0"
});
} else { // Safari
$$.css({
'position' : 'absolute',
'left' : 0,
'background' : ''
});
}
// similar effect as single image technique, except using .animate
// which will handle the fading up from the right opacity for us
$$.hover(function () {
$$.stop().animate({
opacity: 0
}, 450);
}, function () {
$$.stop().animate({
opacity: 1
}, 1000);
});
});
};
})(jQuery);
// note that this uses the .bind('load') on the window object, rather than $(document).ready()
// because .ready() fires before the images have loaded, but we need to fire *after* because
// our code relies on the dimensions of the images already in place.
$(window).bind('load', function () {
$('img.fade').cross();
});
must be the usual bug with positioning in IE. I would recommend reading the first answer from IE7 relative/absolute positioning bug with dynamically modified page content and see if that helps solve your problem.
try change your code to below, it should fix the photos on your right hand side. =)
// the CSS styling of the start image needs to be handled
// differently for different browsers
if ($.browser.msie || $.browser.mozilla) {
$$.css({
'position' : 'absolute',
'left' : 0,
'background' : ''
});

How to display a message on screen without refreshing like SO does? [duplicate]

This is the first time I visited stack overflow and I saw a beautiful header message which displays a text and a close button.
The header bar is fixed one and is great to get the attention of the visitor. I was wondering if anyone of you guys know the code to get the same kind of header bar.
Quick pure JavaScript implementation:
function MessageBar() {
// CSS styling:
var css = function(el,s) {
for (var i in s) {
el.style[i] = s[i];
}
return el;
},
// Create the element:
bar = css(document.createElement('div'), {
top: 0,
left: 0,
position: 'fixed',
background: 'orange',
width: '100%',
padding: '10px',
textAlign: 'center'
});
// Inject it:
document.body.appendChild(bar);
// Provide a way to set the message:
this.setMessage = function(message) {
// Clear contents:
while(bar.firstChild) {
bar.removeChild(bar.firstChild);
}
// Append new message:
bar.appendChild(document.createTextNode(message));
};
// Provide a way to toggle visibility:
this.toggleVisibility = function() {
bar.style.display = bar.style.display === 'none' ? 'block' : 'none';
};
}
How to use it:
var myMessageBar = new MessageBar();
myMessageBar.setMessage('hello');
// Toggling visibility is simple:
myMessageBar.toggleVisibility();
Update:
Check out the DEMO
Code Used:
$(function(){
$('#smsg_link').click(function(){
showMessage('#9BED87', 'black', 'This is sample success message');
return false;
});
$('#imsg_link').click(function(){
showMessage('#FFE16B', 'black', 'This is sample info message');
return false;
});
$('#emsg_link').click(function(){
showMessage('#ED869B', 'black', 'This is sample error message');
return false;
});
});
/*
showMessage function by Sarfraz:
-------------------------
Shows fancy message on top of the window
params:
- bgcolor: The background color for the message box
- color: The text color of the message box
- msg: The message text
*/
var interval = null;
function showMessage(bgcolor, color, msg)
{
$('#smsg').remove();
clearInterval(interval);
if (!$('#smsg').is(':visible'))
{
if (!$('#smsg').length)
{
$('<div id="smsg">'+msg+'</div>').appendTo($('body')).css({
position:'fixed',
top:0,
left:0,
width:'98%',
height:'30px',
lineHeight:'30px',
background:bgcolor,
color:color,
zIndex:1000,
padding:'10px',
fontWeight:'bold',
fontSize:'18px',
textAlign:'center',
opacity:0.8,
margin:'auto',
display:'none'
}).slideDown('show');
interval = setTimeout(function(){
$('#smsg').animate({'width':'hide'}, function(){
$('#smsg').remove();
});
}, 3000);
}
}
}
If you want to create your own, check out the slideToggle function of jQuery.
The relevant css would include:
position: fixed;
top: 0;
width: 100%;
More information about position:fixed:
An element with position: fixed is positioned at the specified coordinates relative to the browser window. The element's position is specified with the "left", "top", "right", and "bottom" properties. The element remains at that position regardless of scrolling. Works in IE7 (strict mode)
If IE6 support is important to you, you may wish to research workarounds.
Here is an alternative method using jQuery which would also slide up/down on show/hide.
Add the following HTML right after the <body> tag in your page:
<div id="msgBox">
<span id="msgText">My Message</span>
<a id="msgCloseButton" href='#'>close</a>
</div>
Add this CSS to your stylesheet
#msgBox {
padding:10px;
background-color:Orange;
text-align:center;
display:none;
font:bold 1.4em Verdana;
}
#msgCloseButton{
float:right;
}
And finally here is the javascript to setup the close button and functions to show and hide the message bar:
/* Document Ready */
$(function () {
SetupNotifications();
});
SetupNotifications = function () {
//setup close button in msgBox
$("#msgCloseButton").click(function (e) {
e.preventDefault();
CloseMsg();
});
}
DisplayMsg = function (sMsg) {
//set the message text
$("#msgText").text(sMsg);
//show the message
$('#msgBox').slideDown();
}
CloseMsg = function () {
//hide the message
$('#msgBox').slideUp();
//clear msg text
$("#msgtText").val("");
}
To perform a simple test you could try this:
Show Message!
Something like this?
$("#bar").slideUp();
However, here I think they fade out first the bar then they bring the main container up, so that'd be something like that:
$("#bar").fadeOut(function(){
$("#container").animate({"top":"0px"});
});

Categories