.toggle() on figcaption not working - javascript

I made my caption overlay my image and I wanted to add a display on hover functionality to it. But I can't get it to work
CSS
figure
{
margin: 0;
position: relative;
float: left;
figcaption
{
z-index: 2;
background-color: #ccc;
position: absolute;
left: 0;
bottom: 0;
width: 100%;
}
}
HTML
<figure>
<img src = "http://someimage.com/image.png">
<figcaption id="caption" style = "display: none">
<p> Some caption text </p>
<a href = '#'>link to author's bio</a>
</figcaption>
</figure>
And finally my very simplistic javascript. I know the hover functionality is working correctly because my console has a "hello" when I enter the figure and a "goodbye" when I leave. There is no "complete" message.
JQUERY
<script type = "text/javascript">
$('figure').hover(function ()
{
console.log('hello');
$('figcaption').toggle(slow,function(){ console.log("complete");} );
},
function ()
{
console.log('goodbye');
$('figcaption').toggle(slow,function(){ console.log("complete");});
});
</script>

Put slow in quotation marks since it's a string and it will work:
$('figcaption').toggle("slow",function(){ console.log("complete");} );
Fiddle

You should have an error in the console. Change slow to "slow".
It's a string.
From the documentation :
duration (default: 400) Type: Number or String A string or number
determining how long the animation will run.

You have multiple errors on your page
Check out the fiddle for a working demo
slow should be "slow"
you did not close the image tag
you have one css class nested inside the other
For future reference. Browsers have JavaScript consoles that print debug information. You must know this as you are using console.log(). If your current browser does not print information like:
Uncaught ReferenceError: slow is not defined
I would recommend you tweak your console settings or install a thrird party one. There are many excellent choices out there

Slow is a string:
$('figure').hover(
function(){
console.log('hello');
$('figcaption').toggle("slow",function(){ console.log("complete");} );
},function(){
console.log('goodbye');
$('figcaption').toggle("slow",function(){ console.log("complete");});
});
http://jsfiddle.net/RX5QA/1/

Related

Toggling HTML visibility using CSS and jQuery

Ok so I have a div that contains a canvas and a span which contains an image. I want it such that if the user hovers over or focuses on the div that the image inside of the span will appear. The image wil be invisible otherwise.
Long story short I want to have a canvas with a red 'X' on the corner that is only visible when the canvas is active
$('image-canvas').hover(function() {
$('delete-image').addClass('active');
}, function() {
$('delete-image').removeClass('active');
})
.delete-image {
position: absolute;
top: 0px;
right: 0px;
}
.delete-image>img {
width: 32px;
visibility: hidden;
}
.delete-image.active>img {
width: 32px;
visibility: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="canvas-container" tabindex="1">
<canvas id="imageCanvas"></canvas>
<span class="delete-image">
<img src="file:///E:/Apps/Emoji-App/emojis/icons/if_erase_delete_remove_wipe_out_181387.png"/>
</span>
</div>
The hover event fires just fine but the image refuses to toggle visibility. Any help?
When you use a class within your selector, write it like this:
$('.myDiv')
When you use an ID within your selector, write it like this:
$('#myDiv')
For further informations, check out jQuery's learning center website.
Seems like you have misspelled or have not specified the jQuery selector type (class . or id #). Please try this:
$('#imageCanvas').hover(function () {
$('.delete-image').addClass('active');
}, function () {
$('.delete-image').removeClass('active');
})
See here .
$("#control").mouseover(function(){
$('#img').show();
});
$("#control").mouseout(function(){
$('#img').hide();
});
#img{
display:none;
}
#control{
margin-bottom:10px;
padding:5px;
background-color:#eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='control'>Show/Hide</div>
<img src='https://cdn.sstatic.net/Sites/stackoverflow/img/404.svg' id='img'>
The question is not well-phrased, so I ain't sure I totally understood what you wanted.
When you try to select by class, don't forget the dot '.'
$('image-canvas').hover(function () {
$('.delete-image').addClass('active');
}, function () {
$('.delete-image').removeClass('active');
})
When using functions 'addClass', 'removeClass', 'toggleClass', etc. - you don't use the '.' sign because it is a function that refers only to classes. On the other hand, when using jQuery selector $(' ') or vanilla querySelector(' '), you should declare what kind of attribute you are selecting by, those will be '#' for ID, '.' for Class, and if you want to select by anything else you can use $('*[anyattribute=anyvalue]'), in your clase it could be $('span[class=delete-image]').
Good luck

scrollTo() function does nothing

I wanted to scroll to the bottom of the page using vanilla JS, but I encountered a problem. The code below is supposed to scroll to the bottom of the page:
window.scrollTo(0,document.body.scrollHeight);
Whereas all it does is logs "undefined" in the console. Inputting
document.body.scrollHeight
returns an integer 736. Other than that, it doesn't matter what I input into the function's parameters, nothing happens. What more, it only happens on one website. What may matter (not sure) is that the website hides its vertical scrolling bar, even thought it has a really long list of content.
The problem might be that the actuall scroll that you have on the website is not the scroll of the body but a scroll of another element inside that body.
Here is an example:
$('#btn1').click(function() {
window.scrollTo(0,document.body.scrollHeight);
});
$('#btn2').click(function() {
el = $('.a')[0];
el.scrollTop = el.scrollHeight;
});
body {
overflow: hidden;
margin: 0;
padding: 0;
}
div.a {
height: 100vh;
overflow: auto;
}
div.b {
height: 1500px;
position: relative;
}
div.c {
position: absolute;
bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a">
<div class="b">
<button id="btn1">Scroll body - doesn't work</button><br />
<button id="btn2">Scroll element - will work</button>
<div class="c">This is at bottom of page</div>
</div>
</div>
Note - the usage of jquery is only to make the example shorter.
Put some content in your page o style the body heigth = 1500px for example, then try to execute same code.
Solved. This is what had to be done:
document.getElementsByTagName('body')[0].style.display = "block";
For whatever reason, changing the display to "block" enabled the scrolling using the given code:
window.scrollTo(0,document.body.scrollHeight);
If you will try to type in browser's console like a var a = 5 you also will get undefined. It happens that your example and my did not return anything.

Select <divs> within parent <div> using jQuery

I have a parent <div>, #amwcontentwrapper, which has a series of divs within it with their own classes and ids.
I want to use jQuery to select these child divs, and IF they have the class .amwhidden, do nothing, but if not, remove the .amwshown class and add the .amwhidden class.
This is what I have so far, but it is not working. I think it may be my selecting of the child divs within the parent.
Can anybody see any obvious problems? Thanks for your help.
if ($('#amwcontentwrapper > div').hasClass('amwhidden')){
} else {
$('#amwcontentwrapper > div').fadeIn(600, function(){
$('#amwcontentwrapper > div').removeClass('amwshown');
$('#amwcontentwrapper > div').addClass('amwhidden');
});
}
And here is the basic html that I am using:
<div class="amwshown" id="amwintro">
Intro Section, which should have the 'amwshown' class removed, and the
'amwhidden' class added, when the jQuery runs. Currently, this does not happen.
</div>
UPDATE: Using War10ck's solution in the comments below (i.e. $('#amwcontentwrapper > div.amwshown')) I have managed to get the classes changing as I wished. However, those which have had the .amwshown class removed and .amwhidden class added still show on the page, despite the CSS looking like this:
.amwhidden {
display:none;
}
.amwshown {
display:block;
}
Looking at the Dev Tools, it seems that, when the jQuery is run (on a click event) the classes are changing, but any classes which are having the .amwshown class added (thus displaying them on the page) are also having the a <style> tag added to them which makes them display:block;
When I then press another button, which should hide the aformentioned <div> to make way for another one, the class is being changed to .amwhidden, but that <style> tag is not being deleted, so even though it has the .amwhidden class, it is still on the page.
I've created a JSFiddle here, if anybody still wants to help!
`
$(document).ready(function() {
$('#buybutton').click(function() {
$('#amwcontentwrapper > div.amwshown').fadeIn(600, function() {
$(this).removeClass('amwshown').addClass('amwhidden');
});
if ($('#amwbuy').hasClass('amwshown')) {} else {
$('#amwbuy').fadeIn(600, function() {
$('#amwbuy').removeClass('amwhidden');
$('#amwbuy').addClass('amwshown');
});
}
});
$('#phdbutton').click(function() {
$('#amwcontentwrapper > div.amwshown').fadeIn(600, function() {
$(this).removeClass('amwshown').addClass('amwhidden');
});
if ($('#amwphd').hasClass('amwshown')) {} else {
$('#amwphd').fadeIn(600, function() {
$('#amwphd').removeClass('amwhidden');
$('#amwphd').addClass('amwshown');
});
}
});
});
#sidebar {
position: absolute;
left: 1%;
top: 1%;
font-size: 5em;
color: #000000;
width: 10%;
display: block;
background-color: red;
}
#amwcontentwrapper {
position: absolute;
left: 20%;
top: 5%;
}
.amwshown {
display: block;
}
.amwhidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="amwsidebar">
<span class="sidebarbutton" id="phdbutton">PhD Button</span>
<br />
<br />
<span class="sidebarbutton" id="buybutton">Buy Button</span>
</div>
<div id="amwcontentwrapper">
<div class="amwshown" id="amwintro">
<p>An intro section to welcome the visitor. Disappears when one of the other sections is clicked.</p>
<br />
<br />
</div>
<div class="amwhidden" id="amwbuy">
Buy Section
</div>
<div class="amwhidden" id="amwphd">
PhD Section
</div>
</div>
`
You can use not to remove the elements you do not want, like this:
$('#amwcontentwrapper > div').not('.amwhidden')
.removeClass('amwshown')
.addClass('amwhidden');
And work with that.
Try this
$(document).ready(function() {
$("#amwcontentwrapper").children().each(function(elem, x) {
if ($(x).attr("class") == "amwhidden") {
alert($(x).attr("class"));
$(x).removeClass("amwhidden").addClass("amwshow");
alert($(x).attr("class"));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="amwcontentwrapper">
<div class="amwhidden"></div>
<div></div>
<div></div>
</div>
You can try each as follow,
$("#amwcontentwrapper div").each(function(){
if($(this).hasClass('amwhidden'))
//DO something
else
//DO something
});
Thank you for all help, it has prompted some brainstorming which has solved this issue.
Instead of adding the .amwhidden class and removing the .amwhidden class using jQuery, I have just created a .amwsection class, which all the sections belong to which has an initial display value of none. So far, so good; all of the sections are not there when you load up the page.
Then I use the .css jQuery function to change the display:none to display:block when the corresponding button is clicked, and changing all other .amwsections to display:none. This works just fine, but the effect is quite abrupt; there is no fading in, as you would get if you used the .animate function. .animate, however, does not work with the display value.
.fadeOut and .fadeIn to the rescue! By wrapping the .css change in these, I can create a fading in/out effect and can still use the display value.
Here is one example of this code.
The #buybutton is the button to be pressed.
#amwintro is just something which appears when the page loads - it will now be set to display:none if this is the first button pressed.
The .amwsection are all of the hidden sections. This portion of the code just resets all of them. This and the #amwintro section happen very quickly (1/100th of a second) to keep response time good.
The #amwbuy is the specific section that I want to reveal. As you can see, this fades in over a longer period.
Currently only tested in Chrome, but I think I've got it!
$(document).ready(function () {
$('#buybutton').click(function() {
$('#amwintro').fadeOut(1, function() {
$(this).css({
display:'none',
});
});
$('.amwsection').fadeOut(1, function() {
$(this).css({
display:'none',
});
});
$('#amwbuy').fadeIn(600, function() {
$(this).css({
display:'block',
});
});
});
});

On mouseover, changing an image's opacity and overlaying text

I want to drop the opacity and overlay text on a thumbnail image when I mouse over it. I have several ideas about how to do it, but I'm fairly certain they're inefficient and clumsy.
Make a duplicate image in Photoshop with the text overlay and reduced opacity. Swap the original out for the duplicate on mouseover.
Use CSS to drop the opacity on mouseover. Use Javascript to toggle visibility of a div containing the overlay text.
The problem I see with 1 is it seems like an unnecessary use of space and bandwidth, and will cause slow load times. With 2, it seems like I'd have to hard-code in the location of each div, which would be a pain to maintain and update. I know this is a somewhat general question, but I'm at a loss about how to go about this. How can I do this relatively simple task in a way that will make it easy to add new thumbnails?
Wrap your image in a <div class="thumb">
Add position: relative to .thumb.
Add <div class="text> inside .thumb.
Add display: none; position: absolute; bottom: 0 to .text.
Use .thumb:hover .text { display: block } to make the text visible on hover.
Like this: http://jsfiddle.net/dYxYs/
You could enhance this with some JavaScript/jQuery: http://jsfiddle.net/dYxYs/1/
$('.text').hide().removeClass('text').addClass('text-js');
$('.thumb').hover(function(){
$(this).find('.text-js').fadeToggle();
});
This way, the basic effect still works without JavaScript, and users with JavaScript get the appealing fade effect.
Go with option 2. There are ways to do it to not have to write a jQuery function for each image. As seen in my jsfiddle.
http://jsfiddle.net/daybreaker/dfJHZ/
HTML
<img src="http://placekitten.com/300/300" />
<span class="text" style="display:none">THIS IS A KITTEN</span>
<br><br>
<img src="http://placekitten.com/200/200" />
<span class="text" style="display:none">THIS IS A KITTEN</span>
jQuery
$('img').mouseover(function(){
$(this).css('opacity','.2');
$(this).next('span.text').show();
}).mouseout(function(){
$(this).css('opacity','1');
$(this).next('span.text').hide();
});
You would need to modify the span.text css to overlay it on top of the image, but that shouldnt be too bad.
Wrap it in an element and do something like this:
var t;
$('div.imgwrap img').hover(function(){
t = $('<div />').text($(this).attr('title')).appendTo($(this).parent());
$(this).fadeTo('fast',0.5);
},function(){
$(this).fadeTo('fast',1);
$(t).remove();
});
with a markup similar to:
<div class="imgwrap">
<img src="http://www.gravatar.com/avatar/3d561d41394ff0d5d0715b2695c3dcf0?s=128&d=identicon&r=PG" title="text" />
</div>
example: http://jsfiddle.net/niklasvh/Wtr9W/
Here's an example. You can position the text however you want, but the basic principle below.
http://jsfiddle.net/Xrvha/
#container { position: relative; }
#container img, #container div {
position: absolute;
width: 128px;
height: 128px;
}
#container img { z-index -1; }
#container div {
z-index 1;
line-height: 128px;
opacity: 0;
text-align: center;
}
#container:hover img {
opacity: 0.35;
}
#container:hover div {
opacity: 1;
}
If you don't want to change your HTML wraping things etc, I suggest you this way. Here is the jQuery:
$(function() {
$(".thumb").mouseenter(function() {
var $t = $(this);
var $d = $("<div>");
$d.addClass("desc").text($t.attr("alt")).css({
width: $t.width(),
height: $t.height() - 20,
top: $t.position().top
});
$t.after($d).fadeTo("fast", 0.3);
$d.mouseleave(function() {
$(this).fadeOut("fast", 0, function() {
$(this).remove();
}).siblings("img.thumb").fadeTo("fast", 1.0);
});
});
});
2 is a good solution, have done about the same as this and it isn't as hard as you would've tought;
Drop de opacity with css indeed, than position a div relative to the img, and over it. It can be done with plain css. The z-index is the trick. That div can just be shown with $('#div').slideUp() ie.

open file select dialog with javascript [duplicate]

I'd like to make a click event fire on an <input type="file"> tag programmatically.
Just calling click() doesn't seem to do anything or at least it doesn't pop up a file selection dialog.
I've been experimenting with capturing events using listeners and redirecting the event, but I haven't been able to get that to actually perform the event like someone clicked on it.
I have been searching for solution to this whole day. And these are the conclusions that I have made:
For the security reasons Opera and Firefox don't allow to trigger file input.
The only convenient alternative is to create a "hidden" file input (using opacity, not "hidden" or "display: none"!) and afterwards create the button "below" it. In this way the button is seen but on user click it actually activates the file input.
Upload File
You cannot do that in all browsers, supposedly IE does allow it, but Mozilla and Opera do not.
When you compose a message in GMail, the 'attach files' feature is implemented one way for IE and any browser that supports this, and then implemented another way for Firefox and those browsers that do not.
I don't know why you cannot do it, but one thing that is a security risk, and which you are not allowed to do in any browser, is programmatically set the file name on the HTML File element.
You can fire click() on any browser but some browsers need the element to be visible and focused. Here's a jQuery example:
$('#input_element').show();
$('#input_element').focus();
$('#input_element').click();
$('#input_element').hide();
It works with the hide before the click() but I don't know if it works without calling the show method. Never tried this on Opera, I tested on IE/FF/Safari/Chrome and it works. I hope this will help.
THIS IS POSSIBLE:
Under FF4+, Opera ?, Chrome:
but:
inputElement.click() should be called from user action context! (not script execution context)
<input type="file" /> should be visible (inputElement.style.display !== 'none') (you can hide it with visibility or something other, but not "display" property)
just use a label tag, that way you can hide the input, and make it work through its related label
https://developer.mozilla.org/fr/docs/Web/HTML/Element/Label
For those who understand that you have to overlay an invisible form over the link, but are too lazy to write, I wrote it for you. Well, for me, but might as well share. Comments are welcome.
HTML (Somewhere):
<a id="fileLink" href="javascript:fileBrowse();" onmouseover="fileMove();">File Browse</a>
HTML (Somewhere you don't care about):
<div id="uploadForm" style="filter:alpha(opacity=0); opacity: 0.0; width: 300px; cursor: pointer;">
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
</form>
</div>
JavaScript:
function pageY(el) {
var ot = 0;
while (el && el.offsetParent != el) {
ot += el.offsetTop ? el.offsetTop : 0;
el = el.offsetParent;
}
return ot;
}
function pageX(el) {
var ol = 0;
while (el && el.offsetParent != el) {
ol += el.offsetLeft ? el.offsetLeft : 0;
el = el.offsetParent;
}
return ol;
}
function fileMove() {
if (navigator.appName == "Microsoft Internet Explorer") {
return; // Don't need to do this in IE.
}
var link = document.getElementById("fileLink");
var form = document.getElementById("uploadForm");
var x = pageX(link);
var y = pageY(link);
form.style.position = 'absolute';
form.style.left = x + 'px';
form.style.top = y + 'px';
}
function fileBrowse() {
// This works in IE only. Doesn't do jack in FF. :(
var browseField = document.getElementById("uploadForm").file;
browseField.click();
}
Try this solution: http://code.google.com/p/upload-at-click/
If you want the click method to work on Chrome, Firefox, etc, apply the following style to your input file. It will be perfectly hidden, it's like you do a display: none;
#fileInput {
visibility: hidden;
position: absolute;
top: 0;
left: -5000px;
}
It's that simple, I tested it works!
$(document).one('mousemove', function() { $(element).trigger('click') } );
Worked for me when I ran into similar problem, it's a regular eRube Goldberg.
WORKING SOLUTION
Let me add to this old post, a working solution I used to use that works in probably 80% or more of all browsers both new and old.
The solution is complex yet simple. The first step is to make use of CSS and guise the input file type with "under-elements" that show through as it has an opacity of 0. The next step is to use JavaScript to update its label as needed.
HTML The ID's are simply inserted if you wanted a quick way to access a specific element, the classes however, are a must as they relate to the CSS that sets this whole process up
<div class="file-input wrapper">
<input id="inpFile0" type="file" class="file-input control" />
<div class="file-input content">
<label id="inpFileOutput0" for="inpFileButton" class="file-input output">Click Here</label>
<input id="inpFileButton0" type="button" class="file-input button" value="Select File" />
</div>
</div>
CSS Keep in mind, coloring and font-styles and such are totally your preference, if you use this basic CSS, you can always use after-end mark up to style as you please, this is shown in the jsFiddle listed at the end.
.file-test-area {
border: 1px solid;
margin: .5em;
padding: 1em;
}
.file-input {
cursor: pointer !important;
}
.file-input * {
cursor: pointer !important;
display: inline-block;
}
.file-input.wrapper {
display: inline-block;
font-size: 14px;
height: auto;
overflow: hidden;
position: relative;
width: auto;
}
.file-input.control {
-moz-opacity:0 ;
filter:alpha(opacity: 0);
opacity: 0;
height: 100%;
position: absolute;
text-align: right;
width: 100%;
z-index: 2;
}
.file-input.content {
position: relative;
top: 0px;
left: 0px;
z-index: 1;
}
.file-input.output {
background-color: #FFC;
font-size: .8em;
padding: .2em .2em .2em .4em;
text-align: center;
width: 10em;
}
.file-input.button {
border: none;
font-weight: bold;
margin-left: .25em;
padding: 0 .25em;
}
JavaScript Pure and true, however, some OLDER (retired) browsers may still have trouble with it (like Netscrape 2!)
var inp = document.getElementsByTagName('input');
for (var i=0;i<inp.length;i++) {
if (inp[i].type != 'file') continue;
inp[i].relatedElement = inp[i].parentNode.getElementsByTagName('label')[0];
inp[i].onchange /*= inp[i].onmouseout*/ = function () {
this.relatedElement.innerHTML = this.value;
};
};
Working jsFiddle Example
It works :
For security reasons on Firefox and Opera, you can't fire the click on file input, but you can simulate with MouseEvents :
<script>
click=function(element){
if(element!=null){
try {element.click();}
catch(e) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click",true,true,window,0,0,0,0,0,false,false,false,false,0,null);
element.dispatchEvent(evt);
}
}
};
</script>
<input type="button" value="upload" onclick="click(document.getElementById('inputFile'));"><input type="file" id="inputFile" style="display:none">
I know this is old, and all these solutions are hacks around browser security precautions with real value.
That said, as of today, fileInput.click() works in current Chrome (36.0.1985.125 m) and current Firefox ESR (24.7.0), but not in current IE (11.0.9600.17207). Overlaying a file field with opacity 0 on top of a button works, but I wanted a link element as the visible trigger, and hover underlining doesn't quite work in any browser. It flashes on then disappears, probably the browser thinking through whether hover styling actually applies or not.
But I did find a solution that works in all those browsers. I won't claim to have tested every version of every browser, or that I know it'll continue to work forever, but it appears to meet my needs now.
It's simple: Position the file input field offscreen (position: absolute; top: -5000px), put a label element around it, and trigger the click on the label, instead of the file field itself.
Note that the link does need to be scripted to call the click method of the label, it doesn't do that automatically, like when you click on text inside a label element. Apparently the link element captures the click, and it doesn't make it through to the label.
Note also that this doesn't provide a way to show the currently selected file, since the field is offscreen. I wanted to submit immediately when a file was selected, so that's not a problem for me, but you'll need a somewhat different approach if your situation is different.
JS Fiddle: http://jsfiddle.net/eyedean/1bw357kw/
popFileSelector = function() {
var el = document.getElementById("fileElem");
if (el) {
el.click();
}
};
window.popRightAway = function() {
document.getElementById('log').innerHTML += 'I am right away!<br />';
popFileSelector();
};
window.popWithDelay = function() {
document.getElementById('log').innerHTML += 'I am gonna delay!<br />';
window.setTimeout(function() {
document.getElementById('log').innerHTML += 'I was delayed!<br />';
popFileSelector();
}, 1000);
};
<body>
<form>
<input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)" />
</form>
<a onclick="popRightAway()" href="#">Pop Now</a>
<br />
<a onclick="popWithDelay()" href="#">Pop With 1 Second Delay</a>
<div id="log">Log: <br /></div>
</body>
Here is pure JavaScript solution to this problem. Works well across all browsers
<script>
function upload_image_init(){
var elem = document.getElementById('file');
if(elem && document.createEvent) {
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, false);
elem.dispatchEvent(evt);
}
}
</script>
This code works for me. Is this what you are trying to do?
<input type="file" style="position:absolute;left:-999px;" id="fileinput" />
<button id="addfiles" >Add files</button>
<script language="javascript" type="text/javascript">
$("#addfiles").click(function(){
$("#fileinput").click();
});
</script>
My solution for Safari with jQuery and jQuery-ui:
$("<input type='file' class='ui-helper-hidden-accessible' />").appendTo("body").focus().trigger('click');
There are ways to redirect events to the control but don't expect to be able to easily fire events to the fire control yourself as the browsers will try to block that for (good) security reasons.
If you only need the file dialog to show up when a user clicks something, let's say because you want better looking file upload buttons, then you might want to take a look at what Shaun Inman came up with.
I've been able to achieve keyboard triggering with creative shifting of focus in and out of the control between keydown, keypress & keyup events. YMMV.
My sincere advice is to leave this the alone, because this is a world of browser-incompatibility-pain. Minor browser updates may also block tricks without warning and you may have to keep reinventing hacks to keep it working.
I was researching this a while ago because I wanted to create a custom button that would open the file dialog and start the upload immediately. I just noticed something that might make this possible - firefox seems to open the dialog when you click anywhere on the upload. So the following might do it:
Create a file upload and a separate element containing an image that you want to use as the button
Arrange them to overlap and make the file element backgroud and border transparent so the button is the only thing visible
Add the javascript to make IE open the dialog when the button/file input is clicked
Use an onchange event to submit the form when a file is selected
This is only theoretical since I already used another method to solve the problem but it just might work.
I had a <input type="button"> tag hidden from view. What I did was attaching the "onClick" event to any visible component of any type such as a label. This was done using either Google Chrome's Developer Tools or Mozilla Firefox's Firebug using the right-click "edit HTML" command. In this event specify the following script or something similar:
If you have JQuery:
$('#id_of_component').click();
if not:
document.getElementById('id_of_component').click();
Thanks.
Hey this solution works.
for download we should be using MSBLOB
$scope.getSingleInvoicePDF = function(invoiceNumberEntity) {
var fileName = invoiceNumberEntity + ".pdf";
var pdfDownload = document.createElement("a");
document.body.appendChild(pdfDownload);
AngularWebService.getFileWithSuffix("ezbillpdfget",invoiceNumberEntity,"pdf" ).then(function(returnedJSON) {
var fileBlob = new Blob([returnedJSON.data], {type: 'application/pdf'});
if (navigator.appVersion.toString().indexOf('.NET') > 0) { // for IE browser
window.navigator.msSaveBlob(fileBlob, fileName);
} else { // for other browsers
var fileURL = window.URL.createObjectURL(fileBlob);
pdfDownload.href = fileURL;
pdfDownload.download = fileName;
pdfDownload.click();
}
});
};
For AngularJS or even for normal javascript.
This will now be possible in Firefox 4, with the caveat that it counts as a pop-up window and will therefore be blocked whenever a pop-up window would have been.
Here is solution that work for me:
CSS:
#uploadtruefield {
left: 225px;
opacity: 0;
position: absolute;
right: 0;
top: 266px;
opacity:0;
-moz-opacity:0;
filter:alpha(opacity:0);
width: 270px;
z-index: 2;
}
.uploadmask {
background:url(../img/browse.gif) no-repeat 100% 50%;
}
#uploadmaskfield{
width:132px;
}
HTML with "small" JQuery help:
<div class="uploadmask">
<input id="uploadmaskfield" type="text" name="uploadmaskfield">
</div>
<input id="uploadtruefield" type="file" onchange="$('#uploadmaskfield').val(this.value)" >
Just be sure that maskfied is covered compeltly by true upload field.
You can do this as per answer from Open File Dialog box on <a> tag
<input type="file" id="upload" name="upload" style="visibility: hidden; width: 1px; height: 1px" multiple />
Upload
I found that if input(file) is outside form, then firing click event invokes file dialog.
Hopefully this helps someone - I spent 2 hours banging my head against it:
In IE8 or IE9, if you trigger opening a file input with javascript in any way at all (believe me I've tried them all), it won't let you submit the form using javascript, it will just silently fail.
Submitting the form via a regular submit button may work but calling form.submit(); will silently fail.
I had to resort to overlaying my select file button with a transparent file input which works.
This worked for me:
<script>
function sel_file() {
$("input[name=userfile]").trigger('click');
}
</script>
<input type="file" name="userfile" id="userfile" />
Click
it's not impossible:
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('click', true, true, window);
setTimeout(function(){ document.getElementById('input_field_id').dispatchEvent(evObj); },100);
But somehow it works only if this is in a function which was called via a click-event.
So you might have following setup:
html:
<div onclick="openFileChooser()" class="some_fancy_stuff">Click here to open image chooser</div>
<input type="file" id="input_img">
JavaScript:
function openFileChooser() {
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('click', true, true, window);
setTimeout(function()
{
document.getElementById('input_img').dispatchEvent(evObj);
},100);
}
You can use
<button id="file">select file</button>
<input type="file" name="file" id="file_input" style="display:none;">
<script>
$('#file').click(function() {
$('#file_input').focus().trigger('click');
});
</script>
To do so you can click an invisible, pass-through element over the file input :
function simulateFileClick() {
const div = document.createElement("div")
div.style.visibility = "hidden"
div.style.position = "absolute"
div.style.width = "100%"
div.style.height = "100%"
div.style.pointerEvents = "none"
const fileInput = document.getElementById("fileInput") // or whatever selector you like
fileInput.style.position = "relative"
fileInput.appendChild(div)
const mouseEvent = new MouseEvent("click")
div.dispatchEvent(mouseEvent)
}

Categories