Trigger drop event - javascript

I have a form with an input type="file". I have a div surrounding the input. I then set the input to display:none. In JavaScript, I set that when you select the div, the input gets selected.
That all works nice and dandy, but how can I make it that when you drag a file onto the div, the input should trigger a drop event?
So here's how I would do the click event:
$('#target').click();
I'm looking for something like this:
$('#target').drop();
JSFiddle
$(document).ready(function() {
$('#browseFileDiv').click(function(e) {
$(this).find('input[type="file"]').click();
});
$('#browseFileDiv input').click(function(e) {
e.stopPropagation();
});
});
#browseFileDiv {
height: 200px;
width: 200px;
background-color: orange;
border-radius: 50%;
}
#browseFileDiv > input {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="upload.php" enctype="multipart/form-data" method="POST" id="uploadform">
<div id="browseFileDiv">
<input id="openFile" name="img" type="file" />
</div>
</form>

First, you don't need to wrap the <input type="file"> with a div around it and then with javscript trigger the .click() event for that input file if you click the div, make a <label> for this input file and style it, thus you can trigger the click event with HTML only without the need for javascript:
<label for="openFile" id="browseFile"></label>
<input id="openFile" name="img" type="file">
Updated: Then, as in this JS Fiddle the problem is that you need to return false; for the ondragover and ondrop events
var browseFile = document.getElementById('browseFile');
browseFile.ondragover = function () {
return false;
};
browseFile.ondrop = function (event) {
event.preventDefault && event.preventDefault();
var files = event.dataTransfer.files;
console.log(files);
return false;
};
** Note that the above works for multiple files as well.
Resource: http://html5doctor.com/drag-and-drop-to-server/

$('#browseFileDiv').on('drop', function(){/* code here */}) is probably what you're looking for.
You probably really want to use jQuery UI. Click the view source button.

Related

Text input and output it on page

I was wondering if I can create a text input where users can type some text and then immediately display them on page, same as twitter. I know about alert window or prompt window but I need something different, a text input on website.
Hope it can be done in JavaScript.
Use .keyup() for the input field then replace the content of the output div.
$(".div-input").keyup(function() {
$(".output").html($(this).val());
});
.output {
margin-top: 20px;
font-size: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="div-input" />
<div class="output">
</div>
If you want to display the input on submit, you could attach a .submit() event on a form tag then use appendTo on the div if you want to insert multiple elements;
$(".form-input").submit(function(e) {
e.preventDefault();
var value = $(".div-input").val();
$("<div class='outputs'>" + value + "</div>").appendTo($(".output"));
});
.output {
margin-top: 20px;
}
.outputs {
padding: 20px;
font-size: 2em;
border: 1px solid black;
margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-input">
<input class="div-input">
<button type="submit">Submit</button>
</form>
<div class="output"></div>
you can use this to show your text anywhere on page
<input id="input-name" oninput="outputname.value = this.value">
<output id="outputname" name="outputname" for="input-name"></output>
You can test it here
If you add an eventlistener to the input, you can use that to change the text in your output area on the page. Like this:
const input = document.getElementById('input');
const output = document.getElementById('output');
input.addEventListener('input', (e) => {
output.innerHTML = input.value;
});
<div id="output"></div>
<input type="text" id="input">
HTML:
<p>Input:</p><input id="input" type="text">
<p>Output:<span id="output"></span></p>
Javascript:
// Function To Select Element
function $(element) {
return document.querySelector(element);
}
// We will get the input when calling this function
function getInput() {
return $('#input').value;
}
// The output will be displayed
function output() {
$('#output').innerHTML = getInput();
}
// This function will start our code
function init() {
output();
}
// On keyup our code will initiate
$('#input').addEventListener('keyup', init);
You can test it here: https://codepen.io/anon/pen/ReyGaO?editors=1111
People are downvoting you because this can be done with very basic JavaScript, and questions like this are very unusual because anyone doing a basic JavaScipt course will probably be able to do this.
Theoretically speaking: you can put an input element and a button on the html page, plus an empty div. You can set an event for the button or even for the input for live updating while typing, and write an event handler function to change the content of the empty div. You can either set its content or add a new child to it, so that the previous content still remains.
Practical example: (The code below is live at https://codepen.io/bradib0y/pen/YJLGrb )
<!DOCTYPE html>
<html>
<body>
<p>Click the button to add a new post.</p>
<input id="NewPostField" type="text" value="Some text">
<button onclick="myFunction()">Add new post</button>
<div id="Posts"></div>
<script>
function myFunction() {
var NewPostField = document.getElementById("NewPostField");
var newPost = document.createElement("p");
newPost.innerHTML = NewPostField.value;
var Posts = document.getElementById("Posts");
Posts.appendChild(newPost);
}
</script>
</body>
</html>
you can do it by this
<input id="mainInput" oninput="output.value = this.value">
<output id="output" name="output" for="input-name"></output>
click here to view in jsFiddle

How to trigger focusout event

I have a focusout event
$('.alpha').on("focusout", function () {...});
and I want want to trigger it from somewhere else in the code.
I tried $('#input12').focus().blur();
and also tried $('#input12').trigger("focusout")
edit: I am using a dynamically generated elements.
but no luck there...
the element #input12 has the class name alpha so I expect The focusout event to be triggered.
Is there any way of getting it done?
here is a jsfiddle example of when I am trying to do https://jsfiddle.net/jnmnk68d/
You need to delegate your events to a non-dynamic parent element.
In this example, we listen for focusout events on the form but only fire our function if the event's target matches the selector (in this case ".alpha"). This way the event can be fired on any elements that match now or in the future.
$("form").on("focusout", ".alpha", function() {
console.log("focusout happened!");
});
Here's a full demo which allows you to see how using delegated events we are able to trigger the event on dynamically inserted content.
$(function() {
$("form").on("focusout", ".alpha", function(e) {
console.warn("focusout triggered on " + e.target.outerHTML);
});
//example trigger
//click the link to trigger the event
$("a").on("click", function(e) {
e.preventDefault();
$("#input12").trigger("focusout");
});
//demo injecting content
//click the create button then focus out on the new element to see the delegated event still being fired.
var i = 12;
$("form").on("submit", function(e) {
e.preventDefault();
var id = "input" + (++i);
$(this).find("fieldset").append("<input id='" + id + "' class='alpha' placeholder='" + id + "' />");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<input id="input12" class="alpha" placeholder="input12" />
<input type="submit" value="create new" />
</fieldset>
</form>
trigger on input12
Using [0] on the jQuery element works! Also kontrollanten options works too! And doing a normal trigger on focusout too!
$(".alpha").on("focusout", function(e){
console.log(e.type, true);
});
//option 1
$('#input12')[0].focus(); //vanilla
$('#input12')[0].blur(); //vanilla
//option 2
$('#input12').trigger('focusout');
//option 3
$('#input12').trigger('blur');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="alpha" id="input12" />
Here is a working example taken from the jQuery docs.
var focus = 0,
blur = 0;
$("p")
.focusout(function() {
focus++;
$("#focus-count").text("focusout fired: " + focus + "x");
})
.inputs {
float: left;
margin-right: 1em;
}
.inputs p {
margin-top: 0;
}
<html lang="en">
<head>
<meta charset="utf-8">
<title>focusout demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div class="inputs">
<p>
<input type="text"><br>
<input type="text">
</p>
</div>
<div id="focus-count">focusout fire</div>
</body>
</html>
Maybe if you add your full code I can be of better help?
Hope this helps!
See this code, it will call focusout 1second after focus has happend.
$('.alpha').on("focusout", function() {
console.log('FOCUSOUT!');
});
$('.alpha').on("focus", function() {
var self = $(this);
window.setTimeout(function() {
self.focusout();
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" class="alpha" />
I found out what seemed to be wrong with my code..
first of all I changed my event to use delegation and I connected it to a non dynamic element (element that was not added dynamically) just as some here advised.
I also needed to call the trigger function inside a setTimeout because it turns out that it takes a while to render the dynamically added element, so using the setTimeout did the trick.
Thank you all for helping out!

Show Upload Button on Click of an Image

In my html file, I have a file input that is hidden behind an image, so that when an image is clicked, the window where you search for images shows. The problem is with the submit part, I need a submit button, but I don't want it to show unless the image is clicked.
Then when the button is clicked, I want to reload the page, now with the button not showing (unless the image is clicked again, of course).
Here's my html code:
<form>
<input id="file-input" type="file" file-model="formData.img" style="display: none;"/>
<br>
<button class="btn btn-booking" id = "uploadButton" ng-click = "changeImage(user._id)" style = "display:block; margin: 0 auto; "> Upload </button>
</form>
You can use the CSS display property to hide the form until the image is clicked, then hide the image until the form is submitted, like so:
var hiderImg = document.getElementById('hiderImg');
hiderImg.addEventListener('click', function() {
// hide image, show form
document.forms[0].style.display = "inline";
hiderImg.style.display = "none";
});
document.getElementById('uploadButton').addEventListener('click', function() {
// show image, hide form
hiderImg.style.display = "inline-block";
document.forms[0].style.display = "none";
});
#hiderImg {
height: 200px;
width: 200px;
}
#hiddenForm {
display: none;
}
<img src="https://upload.wikimedia.org/wikipedia/commons/7/74/White_domesticated_duck%2C_stretching.jpg" id="hiderImg" />
<form id="hiddenForm" onsubmit="javascript: return false;">
<input id="file-input" type="file" file-model="formData.img" />
<br>
<button class="btn btn-booking" id = "uploadButton" ng-click = "changeImage(user._id)" style = "display:block; margin: 0 auto; "> Upload </button>
</form>
Note: I added onsubmit="javascript: return false;" to the form just so that it won't try to submit in this example; you can remove that.
Another note: If you want the upload button to display under the Browse bar, remove the display:block; setting from the button.
First of All put this directive to the your image:
ng-show="fileExist"
After that put this in the your controller:
var uplader = angular.element(document.getElementById("file-input"));
uplader.bind("change", function(){
if(uplader.val()){
$scope.fileExist =true;
}else{
$scope.fileExist =false;
}
});
it's kind of watch in the your input file that handle visibilty of your image.

Target input with :focus, even when changing

I have something like this in jQuery
if($("input").is(":focus")){
// do something
}
It has an effect on the focused input like it should. However, when I switch over to a new input that gets the focus instead, the first one is the still having that effect and not the new one. What would be a good way to make it auto update so that the one that is currently focused has the effect? Thanks!
You might use a simple CSS3 rule:
input:focus {
background-color: red;
}
"Do something" on focus; "Undo that thing" on blur
Your example only runs one time and targets only one input: the one with focus. It doesn't respond to changes.
Use jQuery's .on() method to bind event listeners that can respond to changes.
A basic example:
$('input').on('focus', function () {
// do something
$(this).css('background-color','yellow');
});
$('input').on('blur', function () {
// do something
$(this).css('background-color','white');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<input type="text" />
Another example using chaining:
$('input')
.on('focus', function () {
$(this).addClass('highlight');
})
.on('blur', function () {
$(this).removeClass('highlight');
});
input.highlight {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<input type="text" />
Another example using space-separated list of events:
$('input')
.on('focus blur', function () {
$(this).toggleClass('highlight');
});
input.highlight {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<input type="text" />
Does this help?
$('input').on('focusin' function(){
$(this).toggleClass('someClass')
});
$('input').on('focusout' function(){
$(this).toggleClass('someClass')
});
If you're using jQuery, you could attach event handlers to the focus and blur events.
http://api.jquery.com/category/events/form-events/
$(someSelector).on('focus', function(evt) {
//do stuff
})
and
$(someSelector).on('blur', function(evt) {
//do stuff
})
Note that you can use focusin and focusout if you need to listen for event bubbling.

How to onclick outside an input element which is inside a div?

It maybe easy but i can't think anything to find the way when i click outside the textbox to alert something in javascript BUT when i click inside the text nothing to happen.The input text is inside the div element.
So,let's assume that my html is like bellow:
<div id="myone" onclick="javascript: myfunc();">
<input type="text" id="myInput"></input>
</div>
function myfunc()
{
alert('ok');
}
How to change that?
Thank you a lot!
Do this:
var div = document.getElementById('myone');
var funct = function(){
var input = div.querySelector("#myInput");
return false;
};
div.onclick = funct;
You shoud use this condition. e.target !== this
It is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling. This property is very useful in event delegation, when events bubble.
Use it inside your click function like this and see it in action:
$('.divover').on('click', function(e) {
if (e.target !== this) return;
thefunc();
});
var thefunc = function myfunc() {
alert('ok');
}
.divover {
padding: 20px;
background: yellow;
}
span {
background: blue;
color: white;
padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='divover'>somelabel:
<span><input type="text" class="as" name="forename"></span>
</div>
This will work, if you do this carefully.
<div id="myone" onclick="javascript: myfunc();">
//your stuff in the clickable division.
</div>
<div style="position:absolute;">
<!--Adjust this division in such a way that, it comes inside your clickable division--><input
type="text" id="myInput"></input>
</div>
//Your script function/code here
function myfunc()
{
alert('ok');
}

Categories