Swapping text equal in different divs and classes - javascript

I have several boxes of cards on one page, these boxes can come dynamically in different, not upper right corner has a text for the click to open the accordion type content, for each class I have to do an action as below, I think of something Regardless of the number of classes.
*new
I do not know how to explain it, I'll try a summary:
Change the text of only one div when clicking, because when I click on the item in the box it changes all the other texts of the
Other boxes.
$('.change-1').click(function () {
var $mudartxt = $('.mudartexto');
if ($mudartxt.text() == 'expandir')
$mudartxt.text('ocultar');
else {
$mudartxt.text('expandir');
}
});

You need to find the current clicked item.
For that you can use the event object
$('.change-1').click(function (e) {
// Get current target as jquery object
var $target = $(e.currentTarget);
// Find mudartexto in current target.
var $mudartxt = $target.find('.mudartexto');
if ($mudartxt.text() == 'expandir')
$mudartxt.text('ocultar');
else {
$mudartxt.text('expandir');
}
});
.change-1 {
display:inline-block;
width:200px;
height:50px;
text-align: center;
background-color:#dfdfdf;
clear: both;
float: left;
margin-top:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="change-1">
<div class="mudartexto">expandir</div>
</div>
<div class="change-1">
<div class="mudartexto">expandir</div>
</div>
<div class="change-1">
<div class="mudartexto">expandir</div>
</div>
<div class="change-1">
<div class="mudartexto">expandir</div>
</div>

If you are asking how to change text of an element, inside a clicked box, this should do it.
$('.change-1').click(function () {
var $mudartxt = $(this).find('.mudartexto');
if ($mudartxt.text() == 'expandir')
$mudartxt.text('ocultar');
else {
$mudartxt.text('expandir');
}
});

Related

Show and keep div visible while action is within div or input field?

I want to show a div under input field when user click/focus a input field and hide the div when focus is out or User clicks outside the div or input field.
In this fiddle example, when i click input, a div is shown and when i click outside the input field it gets hidden.
But i want to keep the div visible in below conditions :
1. When input is focused/clicked.
2. When click is within the div(.options).
The div should be hidden when:
1. Input is unfocused and click in not within div.
2. Click outside div.
Fiddle URL
You can try using relatedTarget like the following way:
$(function () {
var inputField = $('#input_field');
var optionsResult = $('#options');
inputField.focusin(function (e) {
e.preventDefault();
optionsResult.show();
}).focusout(function (e) {
if(e.relatedTarget){
if(e.relatedTarget.tagName != 'A')
optionsResult.hide();
}
else{
optionsResult.hide();
}
});
});
$(document).on('click', function(e){
if(e.target.tagName == 'HTML'){
$('#options').hide();
}
});
.options{
display:none;
position: absolute;
float: left;
width: 300px;
height: 200px;
background: #eee;
}
a{
display:block;
float: left;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="app">
<div class="header">
<div id="main_container" class="box">
<div class="inputs">
<input id="input_field" type="text" placeholder="Demo account"/>
</div>
<div id="options" class="options">
Common Link
Common Link 2
</div>
</div>
</div>
<div class="Data">
Another Data Set
</div>
</div>
make sure the body tag contains your app and it's full width and height of the window. add en event listener to see if the click event is outside of the options div and not the input field. hide the options div if that is the case.
JsFiddle
body {
height: 100vh;
width: 100%;
}
$(function () {
var inputField = $('#input_field');
var optionsResult = $('#options');
var options = document.querySelector('#options');
// Listen for click events on body
document.body.addEventListener('click', function (event) {
// hide options if click is outside of options div and not the input element
if (!options.contains(event.target) && event.target.id !== 'input_field') {
optionsResult.hide();
}
});
inputField.focusin(function (e) {
e.preventDefault();
optionsResult.show();
});
});

relatedTarget is null in Firefox when onBlur is called

I'm trying to create a help message that will disappear when the user either clicks the toggle button to display the help message or clicks away by clicking elsewhere on the page. The solution appears to be to look at the relatedTarget property of the onblur event and prevent the onblur handler from running when the relatedTarget is the button to toggle the help message. This seems to work in Chrome, but in Firefox and Safari, the relatedTarget property is set to the container div rather than the button, which makes it impossible to distinguish between the toggle button click and a "click away".
I've created a simple demonstrator that illustrates the problem:
let openState = false;
let contentDiv = document.getElementById("show-hide-content");
let accordionDiv = document.getElementById("accordion");
let showHideButton = document.getElementById("show-hide-toggle");
function setOpenState(state) {
openState = state;
if(openState) {
contentDiv.style.visibility = "visible";
contentDiv.focus();
}
else {
contentDiv.style.visibility = "hidden";
}
}
function toggleVisibility(override) {
if (typeof override === "boolean") {
setOpenState(override);
}
else {
setOpenState(!openState);
}
}
function buttonClickHandler(event) {
toggleVisibility();
}
function contentBlurHandler(event) {
if(!accordionDiv.contains(event.relatedTarget)) {
toggleVisibility(false);
}
}
showHideButton.onclick = buttonClickHandler;
contentDiv.onblur = contentBlurHandler;
.parent {
display: flex;
width: 100vw;
height: 100vh;
flex-direction: row;
background-color: #409958;
}
.accordion {
background-color: #28a7c9;
}
.show-hide-content {
visibility: hidden;
background-color: #c91e63;
}
<h1>Show/Hide Test</h1>
<div class="parent">
<div class="drawer">
<div class="accordion" id="accordion">
<button class="show-hide-toggle" id="show-hide-toggle">Show/Hide</button>
<div class="show-hide-content" id="show-hide-content" tabindex="-1">
<p>This is some content that should be shown or hidden depending on the toggle.</p>
</div>
</div>
<div class="spacer">
</div>
</div>
</div>
This code works correctly in Chrome. However, in Firefox, clicking the "Show/Hide" button displays the hidden content, but doesn't hide it when the button is clicked again. As far as I can tell, this is because the onblur handler is hiding the div, and then the onclick handler is toggling it open again, even though I'm checking onblur.relatedTarget to ensure that it's not anywhere inside the drawer.
What is the correct way to detect click-away in Firefox?
The problem is that clicking the <button> doesn't focus it on some browser/OS combinations (notably on macOS except in Chrome), so onblur's event.relatedTarget is null as nothing on the page receives focus. If you SHIFT+TAB from the <div id="show-hide-content">, you'll see that relatedTarget is set as you expect, as the button does receive focus in this scenario.
I would run the code to hide the div off a small timeout, to give the click handler a chance to run first.
In the example below I implemented this suggestion and added some logging to make it easier to see what's going on:
let openState = false;
let contentDiv = document.getElementById("show-hide-content");
let accordionDiv = document.getElementById("accordion");
let showHideButton = document.getElementById("show-hide-toggle");
function setOpenState(state) {
openState = state;
if(openState) {
contentDiv.style.visibility = "visible";
contentDiv.focus();
}
else {
contentDiv.style.visibility = "hidden";
}
}
function buttonClickHandler(event) {
console.log("click, setting openState to", !openState);
setOpenState(!openState);
}
function contentBlurHandler(event) {
console.log("blur, relatedTarget is", event.relatedTarget);
setTimeout(function() {
console.log("blur, after timeout, openState is", openState);
setOpenState(false);
}, 100);
}
showHideButton.onclick = buttonClickHandler;
showHideButton.onmousedown = function() {console.log("button mousedown"); };
contentDiv.onblur = contentBlurHandler;
showHideButton.onfocus = function(ev) { console.log("button onfocus"); }
.parent {
display: flex;
width: 100vw;
height: 100vh;
flex-direction: row;
background-color: #409958;
}
.accordion {
background-color: #28a7c9;
}
.show-hide-content {
visibility: hidden;
background-color: #c91e63;
}
<h1>Show/Hide Test</h1>
<div class="parent">
<div class="drawer">
<div class="accordion" id="accordion">
<button class="show-hide-toggle" id="show-hide-toggle">Show/Hide</button>
<div class="show-hide-content" id="show-hide-content" tabindex="-1">
<p>This is some content that should be shown or hidden depending on the toggle.</p>
</div>
</div>
<div class="spacer">
</div>
</div>
</div>
This happened to me as well on both Safari and Firefox.
I had an use case where I needed to show clear icon/button only when user focused input (with input having value of course). And clicking that icon would make a blur on input and I had check if new focused element is contained within input but since relatedTarget was null I could not check it.
I added dummy span around my clear button and relatedTarget wasnt't null anymore:
<span aria-hidden="true" tabindex="-1" style="outline: none;">
<button>X</button>
</span>
For thoses who just need a specific value from the target, remember, if your application's design and size allows this possibility, that you can just hardcode the value:
onBlur={()=>function(value)}
For a lot of case it could just work, before an automatic, better scaling solution occurs you have this possibility.

Limit selectable divs in a parent div

I'd like to create a product feature selection page where the user needs to select 3 features out of 6. Now, I got to a point where I can limit the number of selectable elements so if 3 elements are selected, the user wont be able to select a 4th one.
I need to modify this so when the user is attempting to select the 4th element, the 1st element they selected becomes unselected and the 4th element becomes selected. I hope it makes sense.
$('div').click(function(e) {
var $et = $(e.target);
if ($et.hasClass('fill')) {
$et.removeClass('fill');
} else {
if ($('.fill').length < 2) {
$et.addClass('fill');
}
}
});
div {
border: 1px solid blue;
height: 25px;
margin-bottom: 5px;
}
.fill {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div id="1">one</div>
<div id="2">two</div>
<div id="3">three</div>
<div id="4">four</div>
This fiddle shows where I'm at with my code: http://jsfiddle.net/MarKP/32/
This fiddle is not mine, but this is exactly what I have right now in my project.
I'm trying to get this done using jQuery or plain JavaScript.
Thank you in advance!
To achieve this you can maintain an array which holds the order in which the elements were clicked. Then, when the limit is hit, you can remove the class from the element which was selected first. Try this:
var selections = [];
var $div = $('div').click(function(e) {
selections.push(this.id);
if (selections.length > 3)
selections.shift(); // remove first item
setState();
});
function setState() {
$div.removeClass('fill');
$div.filter(`#${selections.join(',#')}`).addClass('fill');
}
div {
border: 1px solid blue;
height: 25px;
margin-bottom: 5px;
}
.fill {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="1">one</div>
<div id="2">two</div>
<div id="3">three</div>
<div id="4">four</div>
<div id="5">five</div>
<div id="6">six</div>
Finally, note that jQuery 1.4.4 is massively outdated; nearly 10 years in fact. You need to update it.

change div color with textbox

I am trying to make a small javascript program in which I have a Div that is transparent initially, and contains an editbox inside. But I want that transparent div to become pink if the text inside editbox is not number. How can I do this? I tried something like this but nothing works:
function proz(){
var textbox = document.getElementById("nr").value; / nr is editbox
var div = document.getElementById("proz"); / proz is the transparent div
if (document.getElementById("nr").value == "a"){ / i tried with if var == "a" but nothing.
div.setAtribute("id", "proz2"); /here proz 2 is another pink div, trying to overlay first div
}
}
I am trying with only letter "a" instead of numbers to check if anything works at least...
So any advices please.
Thank you!
Later Edit:
HTML part:
<body>
<div class="patratpunctat">
<h1><center> Panou centrat </center></h1>
<p> Acest panou va fi centrat vertical si orizontal in pagina.</p>
<div class="pportocaliu">
<div class="prosualbastru"> </div>
</div>
<!-- -->
<!-- partea pentru patratul roz cu javascript-->
<div class="proz">
<div class="inputt">
<input type="text" placeholder="Numar interg" name="nrintreg">
</div>
<script>
function check(){
var textbox = document.getElementById("nrintreg").value;
if (document.getElementById("nrintreg").value == "a"){
window.alert('omg')
}
}
</script>
</div>
</div>
</body>
And yes, I am trying to make it instantly. Like if there is something else than a number there, to make the div pink. if it is Number, div remains transparent.
Is something like this what you're going for?
var textbox = document.getElementById("nr"); // nr is editbox
var div = document.getElementById("proz"); // proz is the transparent div
function proz() {
div.style.backgroundColor = textbox.value
}
textbox.addEventListener('input', function(evt) {
proz();
});
#proz {
height:250px;
width:250px;
border:1px solid black;
}
<input type="text" id="nr" />
<div id="proz"></div>
You need to add a change event handler to the editbox (input, textarea?) and execute your code.
Also, don't change the id because then when your code is executed again it will fail at getElementById("proz"). Use a css class instead to format the element.
Here you have a working version (the div will be pink when the value of the input text is a):
var textbox = document.getElementById("nr");
var div = document.getElementById("proz");
textbox.onkeyup = proz;
function proz() {
if (textbox.value == "a") {
div.classList.add("pink");
} else {
div.classList.remove("pink");
}
}
#proz {
width: 100px;
height: 100px;
}
#proz.pink {
background-color: #FF9999;
}
<input id="nr" />
<div id="proz"></div>
I'm not sure exactly what you're trying to achieve but this was my interpretation of what you might want based on your question.This code checks if the input is a number. If it is, then it will do nothing. If it isn't a number, it will make the transparent div around the text box pink. Hope it helps in some way
document.getElementById('nr').addEventListener("keyup", proz);
function proz(){
var textbox = document.getElementById("nr").value;
var div = document.getElementById("proz");
if (isNaN(textbox) == true){
document.getElementById("some-div").style.background = "pink";
}
else
{
document.getElementById("some-div").style.background = ' transparent';
}
}
#some-div
{
position: absolute;
top: 0;
left: 0;
width:200px;
height:200px;
z-index:-1;
}
<div id = "some-div">
<input type="text" id='nr'><br>
</div>

Can't hide other elements while clicking on another

I'm trying to make a toggle which works, but every element I click on creates a stack of these showed elements. Instead I'm trying to hide everything and display only element that I clicked on. Now I can only hide it when I click on the same element twice, which is not what I want. I want to click on one and hide previous ones that were showing.
.totalpoll-choice-image-2 is a bunch of images that always has to be shown. They are what the user clicks on to display hidden description under each image. That description shows up when I click on .totalpoll-choice-image-2. There are 5 images with that class. The next image I click on, I want to hide the previous description box.
My code:
jQuery(document).ready(function() {
var element = document.getElementsByClassName("totalpoll-choice-image-2");
var elements = Array.prototype.slice.call(Array.from( element ) );
console.log(elements);
jQuery(element).each(function(item) {
jQuery(this).unbind('click').click(function(e) {
e.stopPropagation();
var id = jQuery(this).attr("data-id");
console.log(this);
//jQuery("#" + id).css({"display": 'block !important'});
//document.getElementById(id).style.setProperty( 'display', 'block', 'important' );
var descriptionContainer = document.getElementById(id);
var thiss = jQuery(this);
console.log(thiss);
console.log(jQuery(descriptionContainer).not(thiss).hide());
jQuery(descriptionContainer).toggleClass("show");
});
})
})
You can attach event handlers to a group of DOM elements at once with jQuery. So in this case, mixing vanilla JS with jQuery isn't doing you any favors - though it is possible.
I threw together this little example of what it sounds like you're going for.
The script itself is very simple (shown below). The classes and IDs are different, but the idea should be the same:
// Assign click handlers to all items at once
$('.img').click(function(e){
// Turn off all the texts
$('.stuff').hide();
// Show the one you want
$('#' + $(e.target).data('id')).show();
})
https://codepen.io/meltingchocolate/pen/NyzKMp
You may also note that I extracted the ID from the data-id attribute using the .data() method, and attached the event listener with the .click() method. This is the typical way to apply event handlers across a group of jQuery objects.
From what I understood based on your comments you want to show only description of image that has been clicked.
Here is my solution
$('.container').on('click', 'img', function() {
$(this).closest('.container').find('.image-description').addClass('hidden');
$(this).siblings('p').removeClass('hidden');
});
https://jsfiddle.net/rtsj6r41/
Also please mind your jquery version, because unbind() is deprecated since 3.0
You can use event delegation so that you only add your event handler once to the parent of your images. This is usually the best method for keeping work the browser has to do down. Adding and removing classes is a clean method for show and hide, because you can see what is happening by looking at your html along with other benefits like being easily able to check if an item is visible with .hasClass().
jsfiddle: https://jsfiddle.net/0yL5zuab/17/
EXAMPLE HTML
< div class="main" >
<div class="image-parent">
<div class="image">
</div>
<div class="image-descr">
Some text. Some text. Some text.
</div>
</div>
<div class="image-parent">
<div class="image">
</div>
<div class="image-descr">
Some text. Some text. Some text.
</div>
</div>
<div class="image-parent">
<div class="image">
</div>
<div class="image-descr">
Some text. Some text. Some text.
</div>
</div>
<div class="clear">
</div>
</div>
EXAMPLE CSS
.image-parent{
height: 100px;
width: 200px;
float: left;
margin: 5px;
}
.image-parent .image{
background: blue;
height: 50%;
width: 100%;
}
.image-descr{
display: none;
height: 50%;
width: 100%;
}
.show-descr{
display: block;
}
.clear{
clear: both;
}
EXAMPLE JQUERY
$(".main").on("click", ".image-parent", ShowDescription);
function ShowDescription(e) {
var $parent = $(e.target).parent(".image-parent");
var $desc = $parent.find(".image-descr");
$(".image-descr").removeClass("show-descr");
$desc.addClass("show-descr");
}

Categories