I have multiple contenteditable div with onkeypress event like below:
JsFiddle
<script>
function hadd(event){
var val = event.charCode;
if(val == 36){//$ sign
var current = $(this);
console.log("val_c: " + val);
console.log("rh: " + current);
current.append("correct");
}
};
</script>
<div class="example" contenteditable="true" tabindex="-1" onkeypress="hadd(event);">Test</div>
<div class="example" contenteditable="true" tabindex="-1" onkeypress="hadd(event);">Test_2</div>
<div class="example" contenteditable="true" tabindex="-1" onkeypress="hadd(event);">Test_3</div>
What I want is for the hadd(event) to recognize "$(this)". What change should I make? Because I am getting createDocumentFragement error.
Thanks!
You need to add a second parameter and pass the current element.
onkeypress="hadd(event, this);"
And in your code:
function hadd(event, which) {
current = $(which);
//...
}
Or in simple way, you can also use:
function hadd(event) {
current = $(event.target);
//...
}
Working Fiddle: https://jsfiddle.net/wxwz7bab/
Change
var current = $(this);
to
var current = $(event.target);
function hadd(event) {
var current = $(event.target);
//...
}
Related
I need to delete all children of a div after clicking enter.
There is a div and event listener below.
<div id = "area" contenteditable="true"></div>
document.onreadystatechange = function(){
if(document.readyState == 'complete'){
document.getElementById("area").addEventListener("keypress" , public_mode);
}
function public_mode(){
var key = window.event.keyCode;
if (key == 13) {
sendMessage();
}
}
function sendMessage(){
var area = document.getElementById("area");
while (area.firstChild) {
area.removeChild(area.firstChild);
}
}
As you can see the contenteditable elements is added an element in according with clicking enter - it depends on browser what element will be added.In my case I use chrome and here are inserted div.
So, the result after clicking enter on the area but without removing
<div id = "area" contenteditable = "true">
Sckoriy
<div></div>
</div>
and , with removing
<div id = "area" contenteditable = "true">
<div></div>
<div></div>
</div>
But , the needed result is
<div id = "area" contenteditable = "true">
//Empty
</div>
The code mostly works, however there were two main issues.
keyCode is deprecated. you should be using key which turns the syntax of searching for a key into looking for a string. This means instead of 13 you just check to see if key is Enter.
Secondly you need to pass the event to your public_mode function so that you can read the key that has been pressed when the event occurs. You also need to use preventDefault to prevent it from adding a new line after removing everything from the original contentEditable area when it does detect Enter
document.onreadystatechange = function() {
if (document.readyState == 'complete') {
document.getElementById("area").addEventListener("keypress", public_mode);
}
function public_mode(event) {
var key = event.key;
if (key === "Enter") {
event.preventDefault();
sendMessage();
}
}
function sendMessage() {
var area = document.getElementById("area");
while (area.firstChild) area.removeChild(area.firstChild);
}
}
#area {
min-width: 100vw;
border: 1px solid black;
}
<div id="area" contenteditable="true"></div>
You could just set the innerHTML proprety to an empty string;
area.innerHTML = '';
target the dom by id
var s = document.getElementById("area");
save the number of childrens
var num = s.children.length;
and remove the num of childs of element
for(var i=0;i<num;i++){
s.children[0].remove()
}
and inner for some thext
s.innerHTML = "";
Pass the key event as an argument to your function.
Also, if you do not want the newline entered in your div, you can prevent the event from continuing with event.preventDefault().
document.onreadystatechange = function() {
if (document.readyState == 'complete') {
const area = document.getElementById('area')
area.addEventListener('keypress', public_mode);
area.focus();
}
}
function public_mode(event) {
if (window.event.keyCode == 13) {
sendMessage();
event.preventDefault();
}
}
function sendMessage() {
const area = document.getElementById('area');
while (area.firstChild) {
area.removeChild(area.firstChild);
}
}
<div id="area" contenteditable="true">Press Enter to erase me!</div>
Hi guys can someone help me here I want to make a hidden div being displayed after I trigger the event to display and I remove the mouse on that div here is my code
<div id='MainContainer'>
<div id='btn-img' onmouseover='DisplayHidden()'>content 1</div>
<div id='container2'>content 2</div>
</div>
function DisplayHidden()
{
$('#container2').show();
}
is it possible?
I preferred this way because if you want to add more attributes and comparisons parameters you may add it easily and attribute binding is dynamical.
$(document).ready(function(){
$("#MainContainer > div").on("click",function(e){
if(false === !!$(this).attr('data-click')){
$(this).attr("data-click", true);
alert('No');
}else{
alert('Clicking on same div');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='MainContainer'>
<div id='container1'>content 1</div>
<div id='container2'>content 2</div>
</div>
Here is what you could do, using pure javascript.
Bind the click event on the container element and use event.target attribute to check the previous click element and take appropriate action.
Event.target documentation on MDN
document.addEventListener("DOMContentLoaded", function() {
var prevElement = null;
document.querySelector("#MainContainer").addEventListener("click", function(event) {
if (prevElement === event.target) {
console.log("Yes")
} else {
console.log("No");
}
prevElement = event.target;
});
});
<div id='MainContainer'>
<div id='container1'>content 1</div>
<div id='container2'>content 2</div>
</div>
var lastClick = null;
$('div#MainContainer div').click(function() {
var clickedId = $(this).attr('id');
if (clickedId == lastClick) {
alert('Clicked the same div');
}
else {
alert('Clicked on a different div');
lastClick = clickedId;
}
});
Here a simple solution with plain javascript:
var g_lastTarget = null
var g_handleClick = function(e) {
var target = e.currentTarget
if (g_lastTarget === target) {
alert('You clicked the container twice. Container ID = ' + target.id)
}
g_lastTarget = target
}
var c1 = document.getElementById('container1')
var c2 = document.getElementById('container2')
c1.addEventListener('click', g_handleClick)
c2.addEventListener('click', g_handleClick)
Create a common class & use querySelectorAll to select the desirable elements.
Then loop through it attach eventListener method to it.Create a variable to store the id of the currently clicked element. On subsequent click check if the variable value and id is same. If it is same then throw an alert.
var getElements = document.querySelectorAll(".elem");
var clickedElem = "";
getElements.forEach(function(item) {
item.addEventListener('click', function() {
if (item.id === clickedElem) {
alert('Clicking on same div')
} else {
clickedElem = item.id
}
})
})
<div id='MainContainer'>
<div id='container1' class="elem">content 1</div>
<div id='container2' class="elem">content 2</div>
</div>
I do not have a <input> or any form. I want some way to toggle a plain text to something like **** on click of a button.
for example I have
<p id='one'>google_yahoo</p>
<button id='two'>toggle</button>
so when I click the button once, <p> should become:
<p>************</p>
Then when I click the button then I should again get back google_yahoo
But by default I want it be in ***** form.
What I did:
<script>
function myfunction(){
$("#two").click(function(){
$("#one").text("abc");
});
};
</script>
Any straightforward, easy to understand solution anyone?
You need to create some variables to store value of your text. Try it on JSFiddle.
var txt = document.getElementById('one');
var btn = document.getElementById('two');
var visible = 1;
var value = '';
btn.addEventListener('click', function(){
if(visible){
value = txt.innerHTML;
txt.innerHTML = '*'.repeat(value.length);
}else{
txt.innerHTML = value;
}
visible = !visible;
});
var pMemory = null;
$('button').click(function() {
var pElement = $('p').get(0);
if (pMemory === null) {
// save to cache
pMemory = $(pElement).text();
}
if (pMemory === $(pElement).text()) {
$(pElement).text('*'.repeat(pMemory.length));
} else {
$(pElement).text(pMemory);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>google_yahoo</p>
<button>toggle</button>
Using text-security css property as an option.
$(document).ready(function(){
$("#two").on("click", function(){
$("#one").toggleClass("password_field");
})
})
.password_field{
-webkit-text-security:disc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id='one' class="password_field">google_yahoo</p>
<button id='two'>Toggle</button>
I have put together this piece of JavaScript, but I am struggling with the code as I'm a newbie. What I want to do is when a button is clicked it will change the background color opacity. The code below does this, but now I want the button to be reverted to the normal state when I click it again.
How can I do this? Thanks..
Normal state: background="rgba(255,0,0,0.8)"; Pressed state:
background="rgba(255,0,0,0.6)";
function highlight(id) {
document.getElementById(id).style.background="rgba(255,0,0,0.6)";
}
I would use a CSS class:
.opacityClicked{
background:rgba(255,0,0,0.8);
}
.opacityDefault{
background:rgba(255,0,0,0.6);
}
And change your function to:
function highlight(id) {
var element = document.getElementById(id);
element.class = (element.class == "opacityClicked") ? "opacityDefault" : "opacityClicked";
}
Or if you want to use only JavaScript
var isClicked = false;
function highlight(id) {
isClicked = !isClicked;
var element = document.getElementById(id);
element.style.background = (isClicked == true) ? "rgba(255,0,0,0.6)" : "rgba(255,0,0,0.8)";
}
Update(See comments: if you use 2 buttons):
var buttonClicked = null;
function highlight(id) {
if(buttonClicked != null)
{
buttonClicked.style.background = "rgba(255,0,0,0.8)";
}
buttonClicked = document.getElementById(id);
buttonClicked.style.background = "rgba(255,0,0,0.6)";
}
You could do something really quick like this:
First, add a hidden input element to your page like so:
<input type="button" id="foobar" value="FooBar!" onclick="highlight('foobar')" style="background-color:rgba(255,0,0,0.8);" />
<input type="hidden" id="one_neg_one" value="1" /> <= hidden element
Next, put this in your highlight function:
function highlight(id) {
var a = 7;
var o = document.getElementById("one_neg_one");
var newa = (a + (parseInt(o.value) * -1)) * 0.1;
document.getElementById(id).style.background="rgba(255,0,0," + newa + ")";
o.value = o.value * -1;
}
That should work, although I agree with a previous answer that you should use a css class for this.
#Ruben-J answer works fine. There is a syntax error though - you should instead use element.className rather than element.class.
https://developer.mozilla.org/en-US/docs/Web/API/Element/className
Below is an updated answer using the correct syntax:
function highlight(id) {
var element = document.getElementById(id);
element.className = (element.className == "opacityClicked") ? "opacityDefault" : "opacityClicked";
}
Also noticed that this answer doesn't show the HTML. Make sure to pass through the id element, not the name of the id.
I have the following mark-up:
$(document).ready(function () {
$('.lalala').bind('blur', function (e) {
CheckFirstInput($(this));
});
});
<div id="divContainer">
<input type="text" class="lalala" />
<p id="img1"></p>
</div>
And the following script
function CheckFirstInput(element) {
var txtLength = element.val();
var parent;
var lastElement;
if (txtLength.length < 1) {
parent = element.parent();
lastElement = parent.last();
lastElement.text('prazno e');
}
else {
//element.parent().lastChild().text('4884384f384r34rf');
parent = element.parent();
lastElement = parent.last();
lastElement.text('ne e prazno');
}
}
If the input field is not empty I want to select the last element of the wrapping div (<p>) and change its text. How do I do that?
Thanks in advance!!
You needed to select the children() of the element's parent. You were selecting the last parent. (Which is the parent.)
The following is working. I also cleaned up the code a bit.
$('.lalala').blur( function () {
CheckFirstInput($(this));
});
function CheckFirstInput(element) {
if (element.val().length < 1) {
element.siblings(':last').html('prazno e');
}
else {
element.siblings(':last').html('ne e prazno ');
}
}
Working Fiddle
http://jsfiddle.net/CRccw/2/
If i got it right you could check $(element).is(":empty") and use parent.siblings(":last-child")
Your question has been answered, but here is another way to do it:
$('.lalala').bind('blur', function (e) {
CheckFirstInput($(this));
});
function CheckFirstInput($el) {
var $last = $el.siblings().filter(':last');
var html = ($el.val() == '') ? 'prazno e' : 'ne e prazno';
$last.html(html);
}
DEMO