Need help about a function - javascript

I am new at Javascript and jQuery. I need help with something like:
<script type="text/javascript">
$(window).load(function(){
$('#createDiv').click(function (){
$("<div/>").html("<span id='myInstance2' style='display: block;'>New Folder</span>").css("display", "none").appendTo("#results").fadeIn();
});
});
</script>
I have this function to click and create a new <span> tag with a text. You can see I have an ID myInstance2. So what I am trying to do is when I click and the span is created, I would like to make this span live-editable. Like I can rename this "New folder" into whatever I want.
If anyone can help it would be great. Thanks in advance and sorry for my bad English :)

If I catch what I think you're trying to do, it's not quite feasable the way you imagine. However, there are tricks. The following is one of them. The idea is to insert a "hidden" input where the span is, then create functions to show the input and hide span when needed (like when user clicks on span. Something like so:
jsFiddle
HTML
<button id="createDiv">Start</button>
<div id="results"></div>
CSS
#createDiv, #results span { cursor: pointer; }
#results div {
background: #FFA;
border: 1px solid;
margin: 1em;
padding: 1em 1em 2em;
}
#results input[type=text] {
border: none;
display: none;
outline: none;
}
JavaScript
// Call for document .onload event
$(function() {
// Normal Click event asignement, same as $("#createDiv").click(function
$("#createDiv").on("click", function(e) {
// Simply creating the elements one by one to remove confusion
var newDiv = $("<div />", { class: "new-folder" }), // Notice, each child variable is appended to parent
newInp = $("<input />", { type: "text", value: "New Folder", class: "title-inp" }).appendTo(newDiv),
newSpan = $("<span />", { id: "myInstance2", text: "New Folder", class: "title-span" }).appendTo(newDiv);
// Everything created and seated, let's append this new div to it's parent
$("#results").append(newDiv);
});
// the following use the ".delegate" side of .on
// This means that ALL future created elements with the same classname,
// inside the same parent will have this same event function added
$("#results").on("click", ".new-folder .title-span", function(e) {
// This hides our span as it was clicked on and shows our trick input,
// also places focus on input
$(this).hide().prev().show().focus();
});
$("#results").on("blur", ".new-folder .title-inp", function(e) {
// tells the browser, when user clicks away from input, hide input and show span
// also replaces text in span with new text in input
$(this).hide().next().text($(this).val()).show();
});
// The following sures we get the same functionality from blur on Enter key being pressed
$("#results").on("keyup", ".new-folder .title-inp", function(e) {
// Here we grab the key code for the "Enter" key
var eKey = e.which || e.keyCode;
if (eKey == 13) { // if enter key was pressed then hide input, show span, replace text
$(this).hide().next().text($(this).val()).show();
}
});
})

what you can do is put a delegated event handler on the enclosing, static element where span will reside #results. The handler will hide the span and reveal an input. I don't know your code well enough but you likely want the id on the input instead of the span. You did not say you wanted to go from editable back to "read-only" so I did not do that.
DEMO
$('#createDiv').on('click', function () {
var str = "Click here to edit it"; // New Folder
$("<div/>").html("<span id='myInstance2' class='editToggler' style='display: block;'>" + str + "</span><input class='editToggler' style='display: none' value='" + str + "'/>").appendTo("#results").fadeIn();
$(this).off('click');
});
$('#results').on('click', 'span', function () {
$('.editToggler').toggle();
});

This should work and is much simpler than other answers (imo):
<script type="text/javascript">
$(window).load(function(){
$('#createDiv').click(function (){
$("<div />").html("<span onclick='$(this).html(prompt(\"Rename \"+$(this).html()))' id='myInstance2' style='display: block; cursor:pointer;'>New Folder</span>").css("display", "none").appendTo("#results").fadeIn();
});
});
</script>
When you click your span, you will be prompted for its new name. To visual represent that your created the span is clickable, I also added cursor:pointer to the style for the span.
Demo: http://jsfiddle.net/XJ6Cn/
Edit: P.S: Do you create more than one spanusing this method? If so, you should create the ids dynamically, because ids are meant to be unique. If you want a string to be the same for all spans, you can set it as a class instead.

Related

jquery getting an 'undefined' on the id of a div element I'm trying to grab

So I am dynamically generating HTML code with JavaScript that loads in all my images from my Firebase Realtime Database. I'm currently working on implementing a button attached to each image that will delete this image when clicked. However, after multiple attempts to grab this div's ID attribute using both standard JavaScript and Jquery, the id in the alert box is always 'undefined'. Inspecting the webpage allows me to see that the image's id is always loaded in just fine, so I know it is there.
This is the HTML Generated that I'm trying to interact with.
JavaScript function to respond to my html 'onclick event'
function deleteFile(){
var postId = $(this).closest('div').attr('id');
alert("You have selected id: " + postId);
var sure = confirm("Are you sure you want to delete this post?");
if(sure){
firebase.database().ref().child('Posts/' + postId).remove().then(function(){
alert("Post deleted sucessfully");
});
}
};
Attached image is what html is generated on the actual chrome inspector. The ID's of course will all be unique.
add this parameter on your html onclick attribute so it become deleteFile(this)
then on your js
function deleteFile(element){
var postId = $(element).closest('div').attr('id');
alert("You have selected id: " + postId);
var sure = confirm("Are you sure you want to delete this post?");
if(sure){
firebase.database().ref().child('Posts/' + postId).remove().then(function(){
alert("Post deleted sucessfully");
});
}
};
Pairing onclick with $(this) won't work as you expect because $(this) has a different context, you could view its value using console.log($(this));
What should be done is add a class to that button and bind an onclick event via jquery. Run snippet below.
Red div contains onclick event attached via jquery.
Yellow div contains onclick event attached to the button attribute onclick.
$(document).ready(function(){
$(".getIdButton").click(function() {
alert($(this).closest("div").attr("id"));
});
});
function getId() {
alert($(this).closest("div").attr("id"));
console.log($(this));
}
div {
width: 100px;
height: 100px;
padding: 20px;
display: inline-block;
}
#red {
background-color: red;
}
#yellow {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="red">
Just a link
<button class="getIdButton">Click Me</button>
</div>
<div id="yellow">
Just a link
<button onclick="getId()">Click Me</button>
</div>

mouseover event propagation issue - Manually propagate

I am implementing an User Interface for a project I'm working on and can be found here : Toobrok
Each time the mouse of the user enters a div, a class is added to this div to highlight it, I use the stopPropagation() method to restrict the highlighting to the div whose z-index is higher (the top div in the z axis).
However, sometimes, my user needs to select an element hidden by another one, when the dimensions of the 2 elements are different, and if the bottom div is larger, he can find some points of the bottom div not hidden by the top one, but when the dimensions are the same, I would like the user to be able to press a key to change the depth (on the z-axis) of his selection.
The relevant code is given below (in CoffeeScript), but a javascript solution would also help me:
Ui.bind = (elements, index) ->
ids = Ui.getIdSelector(elements)
$(ids).attr("centroid", index)
$(ids).mouseover (event) ->
event.stopPropagation()
Ui.highlight $(ids)
$(ids).mouseout (event) ->
event.stopPropagation()
Ui.resetHighlight $(ids)
I hope the question is clear and looking forward to your answer.
This is an example of HTML to consider :
<!DOCTYPE html>
<html>
<head>
<title> Sample page </title>
</head>
<body>
<div id="container">
<div id="child1">Some text...</div>
</div>
</body
</html>
And the related css :
#container {
height: 200px;
width: 500px;
}
#child1 {
height: 90%;
width: 90%;
}
When the mouse enters the child1 element, this element is highlighted, I want the container element to highlight when the user press a specific key.
I could use the JQuery parent() function to select that element on this example, but I am not sure it is a good solution, sometimes, the parent can have a size of 0px and and then a mouseover on this element would not be consistent. I want to select the element normally selected by Javascript if I do not use the stopPropagation() event.
I actually just found something that might help :
How to undo event.stopPropagation in jQuery?
But I cannot use that in my case... Because my condition is another user action, and I cannot synchronously wait for an user to do something.
I started writing code but then decided to leave implementation to you. Here is the text explanation:
At some point of time (probably when user press button to cycle through all hovered elements) you have to find all candidates for highlighting. There is no other way to do it rather than manually loop through all your elements and check if mouse position is inside their bound rect. You can get mouse coordinates from argument in mouseover callback. Save all these hovered elements in some array.
Next, you have to manually choose which element to highlight. Just highlight the first element in saved array and move the element to the end of array. You also may want to increase this element z-index and add callback for mouseout to this element.
Hope it helps, feel free to ask if you need more details.
You could use the CSS property pointer-events to make the child insensitive. Then events will be targeted to the element displayed below. For simple highlighting you should use pure CSS, however, jQuery can be helpful not to highlight the parent element as well while child is hovered without Ctrl.
Some example (also uploaded to JSFiddle, click into the output pane to make it responsive for keyboard events):
<div id="container1" class="container">
<div id="child1" class="child">Some text...</div>
</div>
div { border:1px dashed red; } /* for demo */
.container
{ height: 200px;
width: 500px;
}
.child
{ height: 90%;
width: 90%;
}
.insensitive
{ pointer-events:none;
}
.container:hover:not(.no-hilight),
.child:hover
{ background-color:yellow;
}
/* other color for demo */
.child:hover{ background-color:green; }
// make events passthrough child when <Ctrl> is held down
$(document).on('keydown keyup', function(ev) {
if (ev.key === 'Control') // for performance
$('.child')[ev.ctrlKey?'addClass':'removeClass']('insensitive');
});
// don't hilight container when child is hovered
$('.child').on('mouseover', function(ev)
{
$('.container').addClass('no-hilight');
});
// never suppress hilight when container is hovered directly
$('.container').on('mouseover', function(ev)
{ if(ev.target === ev.currentTarget)
$('.container').removeClass('no-hilight');
});
// just test which element a click is targeted to
$(document).on('click', function(ev)
{ console.log('click:', ev.target);
});
var preId = 0;
function makeBlack(id)
{
if(id)
{
$('#'+id).css('border-color','black');
}
}
function makered(id)
{
$('#'+id).css('border-color','red');
}
$(document).ready(function(){
$('div').mouseout(function() {
var currentid = this.id;
makeBlack(currentid);
preId = currentid;
});
$('div').mouseleave(function() {
var currentid = this.id;
makeBlack(currentid);
preId = currentid;
});
$('div').mouseover(function() {
var currentid = this.id;
makeBlack(currentid);
makered(preId);
preId = currentid;
});
$('div').mouseenter(function() {
var currentid = this.id;
makered(currentid);
preId = currentid;
});
});
Have you tried something like this for the CSS?
#container.hover{
height: 200px;
width: 500px;
//add a background-color to that element since its a div element
//background-color: (colour)
}
i should hope that the div element would automatically highlight the container div with whichever color you have selected

Can't figure out adding/removing classes with jquery

I need help with this JS code for my wordpress theme.
First part is when it looks for h4 heading and if it has certain text it wraps all paragraphs below this h4 into div (which hides all paragraphs into fading section) and adds "button" (which is span):
var tutustu = 'TUTUSTU';
var syvenny = 'SYVENNY';
$('.article_content h4').each(function(){
if($(this).text() == tutustu)
{
$(this).nextUntil("h4").wrapAll('<div class="expand" />').parent().append('<span id="expand">show more</span>');
}
else if($(this).text() == syvenny) {
$(this).nextUntil("h4").wrapAll('<div class="expand" />').parent().append('<span id="expand">show more</span>');
}
});
Second is when user clicks on "button" div (that we wrapped into all paragraphs early) will get another class (to basicaly reveal all the paragraphs) and remover button:
$('span#expand').click(function() {
$(this).parent('.expand').removeClass('expand').addClass('expanded');
$(this).remove();
});
What I need is after paragraph text is revealed I want to have button to click on and everything goes back like in 1st part.
I came up with something like this:
$('span#expanded').click(function() {
$(this).parent('.expanded').removeClass('expanded').addClass('expand');
});
But it doesn't work (
Help is much appreciated
Use event Delegation and .toggleClass() instead of .addClass() and .removeClass()
$(document).on("click" , "span#expanded" , function() {
$(this).parent().toggleClass('expanded expand');
});
$('#expanded').on('click', function(e) {
$(this).parent().toggleClass('expanded expand');
e.preventDefault();
});

Performing Action while clicking a text to remove a Div

I have an Example what I get this from one of my previous post .I am trying to upgrade this with my need but I failing . I guess it's because of my lack of knowledge in jquery and JavaScripts . But I need this badly .
Here is Live demo in js fiddle :http://jsfiddle.net/qzKWD/5/
What I have now:
There you can see I have a button . If I click the button it will open a Div with Editable input , where I can rename the input and save . you can create many div by clicking the button and rename as you want .
What I am trying to do
What I was trying to Do is that ,I added a "X" text there . When I click the button "START" new div created with input to change name , also with this "X" text . What I am mainly trying is .. before I rename he input if I don't what that div I can remove the div with input by clicking the "X" text . SO that mean "X" will act as a close of that Div .But I am not finding any way to do that . May be because of my lacking of knowledge . If there is any solution or way it will be Excellent .
My code :
HTML
<button id="createDiv">Start</button>
<div id="results"></div>
CSS
#createDiv, #results span { cursor: pointer; }
#results div {
background: #FFA;
border: 1px solid;
width:auto;
}
#results input[type=text] {
border: none;
display: none;
outline: none;
}
.clickToCancleIcon{
float: right;
}
.new-folder{
height:30px;
float:left;
}
JS
// Call for document .onload event
$(function() {
// Normal Click event asignement, same as $("#createDiv").click(function
$("#createDiv").on("click", function(e) {
// Simply creating the elements one by one to remove confusion
var newDiv = $("<div />", { class: "new-folder" }), // Notice, each child variable is appended to parent
newInp = $("<input />", { name: "inpTitle[]",style:"display:block ;float:left; border:solid 1px #fa9a34", type: "text", value: "Unnamed Group", class: "title-inp" }).appendTo(newDiv),
newSpan = $("<span />", { id: "myInstance2",style:"display:none; float:left;", text: "Unnamed Group", class: "title-span" }).appendTo(newDiv),
clickToCancle = $("<a />", { text: "X", class: "clickToCancleIcon" }).appendTo(newDiv);
// Everything created and seated, let's append this new div to it's parent
$("#results").append(newDiv);
});
// the following use the ".delegate" side of .on
// This means that ALL future created elements with the same classname,
// inside the same parent will have this same event function added
$("#results").on("click", ".new-folder .title-span", function(e) {
// This hides our span as it was clicked on and shows our trick input,
// also places focus on input
$(this).hide().prev().show().focus();
});
$("#results").on("blur", ".new-folder .title-inp", function(e) {
// tells the browser, when user clicks away from input, hide input and show span
// also replaces text in span with new text in input
$(this).hide().next().text($(this).val()).show();
});
// The following sures we get the same functionality from blur on Enter key being pressed
$("#results").on("keyup", ".new-folder .title-inp", function(e) {
// Here we grab the key code for the "Enter" key
var eKey = e.which || e.keyCode;
if (eKey == 13) { // if enter key was pressed then hide input, show span, replace text
$(this).hide().next().text($(this).val()).show();
}
});
})
Just add the following code,
clickToCancle.click(function() {
$(newDiv).remove();
});
After,
clickToCancle = $("<a />", { text: "X", class: "clickToCancleIcon" }).appendTo(newDiv);
Or you can done this by,
clickToCancle = $("<a />", { text: "X", class: "clickToCancleIcon" }).appendTo(newDiv).click(function() {
$(newDiv).remove();
});
See the live DEMO

remove the hidden values and <br> when replacing via .html

I have a code which allows me to add certain "absentees", along with their ID's through a hidden form, to the absentees list when I click on them. When I click on it again, the "absentee" is removed from the absentees list. However, when I click on it again, the list seems to extend further because of a br
in my code plus the hidden form value doesn't seem to be removed. I need the hidden value removed so that the removed absentee from the list will not be recorded in the database. I need the br
so that the absentee listing will be presentable.
Here's my code: http://jsfiddle.net/gk5pV/8/
I wholeheartedly agree with #charlietfl, just use a block level element. Also, use a single hidden input to track your absentees. Example fiddle, code below:
$(function() {
$("td").click(function() {
var $this = $(this);
var user = $this.attr('id');
var p = $('<p />').attr('user', user).text($this.text());
var absentees = [];
if ($('#absentees').val().length > 0) {
absentees = $('#absentees').val().split(',')
}
if ($(this).hasClass('on')) {
//console.log("Already marked absent");
//remove from collection
$("#collect").children('p[user="' + user + '"]').remove();
absentees.splice(absentees.indexOf(user), 1);
}
else {
//console.log(user);
//add to collection
$("#collect").append(p);
absentees.push(user);
}
$this.toggleClass('on');
$('#absentees').val(absentees.join(','));
});
$("#clicky").click(function() {
$('td').removeClass('on');
$("#collect").empty();
$('#absentees').val('');
});
});​
Solution is fairly simple. Wrap the text you want to append and hidden input in a block level element ( div, p, li etc) and you won't need a <br tag. WHen you remove the absentee from list you remove the block element and the input will be part of it so it will no longer exist. If you give the new block level element a class name you can simply attach your event handler to the class

Categories

Resources