When click element it appear elsewhere javascript/jquery - javascript

I need a JavaScript / jQuery code that will allow me when I click one of the elements "A" or "B" to appear in a place (span tags).
It's basically a selection and a display of that selection, when i click element "B", in the span tag should appear "B", if click on "A" then element "A" will appear in the span tag.
<!-- Where should be displayed elements A or B -->
<span>...</span>
<!-- The elements to click on -->
<h1>A</h1>
<h1>B</h1>

use click event and text.
$('h1').click((e) => { $('span').text($(e.target).text());})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span>...</span>
<h1>A</h1>
<h1>B</h1>

Possible solution with pure Javascript could be:
const headings = document.querySelectorAll('.heading');
const result = document.querySelector('#result');
headings.forEach(heading => {
heading.addEventListener('click', () => {
result.innerText = heading.innerText;
});
});
It's good to identify the elements on the page somehow, here I placed an id = "result" on the span element, and class = "heading" to both headings A and B (you could also select those elements with document.getElementsByTagName when you haven't got any better identifiers like classes and IDs). I grabbed the elements from the DOM and stored them in variables. Then you just loop through the headings and add click event listeners to them, on the click you take the innerText from the clicked heading and place it as innerText into the span.

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<!-- Where should be displayed elements A or B -->
<span>...</span>
<!-- The elements to click on -->
<h1>A</h1>
<h1>B</h1>
<script>
/**
* Quick solution without changing the html markup
* could be something like this. But it could be
* improved with better markup thus there could be
* better structured script. It's pure JS.
*/
// Select the element where the value of selection
// should be outputed.
const output = document.querySelector('span');
// Select all elements that are considered an option.
const variant = document.querySelectorAll('h1');
// Elements are in array, so you need to loop through
// them. For loop performs better than forEach.
// We need some counter, we name it i, but you can
// name it anything you want. Arrays are 0 indexed,
// so we assign the initial value 0. Next we need
// a condition, how long should the loop run.
// So as long it’s less than count of variants,
// perform the actions. Last in the for loop is
// what should happen after sequention, we increment
// our counter i by one, alternative of i++ could be
// i += 1.
for (let i = 0; i < variant.length; i++) {
// We take variant[i] - starting from 0 to 1 and then
// we add event listener, that listens for clicks.
// After variant is clicked, we pass an anonymous
// function.
variant[i].addEventListener('click', () => {
// This function simply takes the inner text
// of variant and makes it inner text of
// the output.
output.innerText = variant[i].innerText;
});
}
</script>
</body>
</html>

Related

Detect click on text part of a block element

I have the following html element:
<h1>Some text</h1>
I need to detect a click and recognize whether it landed on the text part or the blank part of the element.
To preserve consistency of the rest of the app I cannot change the display of this element to inline or inline-block.
I also cannot modify the inner html of this element so splitting it into two <span> elements is not an option either.
The text inside this element is not constant and is in fact editable.
Can I detect a click only on the visible (text) part of this heading?
QUESTION "I also cannot modify the inner html of this element so splitting it into two elements is not an option either." does this mean after the fact or before the fact? i.e is it that you cannot alter the HTML or that you can't go in and mutate the HTML via JS ?
Current Solution:
I parse all elements with the .clickable identifier, remove & rebuild their text contents and place spans around them - this way i can add click listeners to the individual text/span elements - giving me access to the text itself.
const clickables = document.querySelectorAll('.clickable')
clickables.forEach(el => new Clickable(el))
function Clickable (el) {
const _handleClick = ({target}) => console.log(target.innerHTML)
const texts = el.textContent.split(/\s/)
el.innerHTML = ''
texts.forEach(t => {
const span = document.createElement('span')
span.innerHTML = `${t} `
span.addEventListener('click', _handleClick)
el.appendChild(span)
})
}
<h1 class="clickable">Some text</h1>
<h2 class="clickable">Some! more! text2</h1>
By the use of Jquery you can use the .click function to know if the h1 tag is clicked.
$('#test').click(function(){
alert("Clicked!");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id='test'>TEST</h1>

Getting Element

I am new to this and I have this element and I have to somehow "get it". There are few more element above it, there's just an element I need:
<a class="btn_green" href="javascript:void(0)" onclick="ShowPopup( 440, "some_text", "some_text" ); return false;">
<span>Some text</span>
</a>
Thanks for help!
$('a.btn_green') will return an array of you could use the Array index to access the proper value if the index is known and does not change
var $a = $('a.btn_green');
var el = $a[2];
You can use getElementsByClassName.
document.getElementsByClassName('btn_green')
This will return an array of all the elements that match. If you have only one element you can access it at index 0.
document.getElementsByClassName('btn_green')[0]
If you added an ID to the element,and then use getElementById
<a id="YOUR_ID_HERE" class="btn_green" href="javascript:void(0)" onclick="ShowPopup( 440, "some_text", "some_text" ); return false;">
document.getElementById('YOUR_ID_HERE')
You can do something like this in standard JS you would do something similar to this:
var button = document.getElementsByClassName('btn_green');
If you're just looking to get that specific element I would suggest adding an id
<a class="btn_green" id="myButton" href="javascript:void(0)" onclick="ShowPopup( 440, "some_text", "some_text" ); return false;">
<span>Some text</span>
</a>
And here is the JS
var button = document.getElementById('myButton');
Details are commented in the Snippet. The anchor in OP's code is atrocious so I made the markup simpler, but the code provided here will work an any anchor(s) under certain conditions described below.
SNIPPET
/* Plain JavaScript */
/* If there is only one element that has the class="btn_green" */
// By className
var btnByClassName = document.querySelector(".btn_green");
/* If it is the only link (anchor)
*/
// By tagName
var btnByTagName = document.querySelector("a");
/* If theres more than one element with the class="btn_green" */
// By className
var btnsByClassName1 = document.querySelectorAll(".btn_green");
// or
var btnsByClassName2 = document.getElementsByClassName("btn_green");
/* The two methods above will collect all elements with the
specified className. The group of elements collected is known
as a HTML Collection or NodeList. If you need to specifically
target one of them out of a group, say like the 2nd one, you have
to count from 0. Ex. the second element in a NodeList would be 1.
*/
/* Continuing from the previous example above, we can single out a
single element by placing the 0 count number of that element:
*/
var btnsByClassNameA = document.querySelectorAll(".btn_green")[1];
//or
var btnsByClassNameB = document.getElementsByClassName("btn_green")[1];
/* A different type of NodeList/HTML Collection can be had by
targeting the tagName, this example we are targeting the first
anchor:
*/
var btnsByTagName1 = document.querySelectorAll("a")[0];
//or
var btnsByTagName2 = document.getElementsByTagName("a")[0];
/* Note: Although these methods are able to get a group of
elements, they are able to get an element if it is the only
one of it's kind by using [0].
*/
/* jQuery */
/* jQuery makes it easier and does most of the thinking for us.
You must make sure that your page has the jQuery library loaded.
Look at the HTML section below, you'll see a <script... tag. You
must have that tag inside the <head></head> or before the </body>
otherwise you code will not function.
*/
/* Note the variable has a $ prefix. This is optional and it's
purpose is to show other developers that the variable represents a
jQuery Object.
*/
// By className
var $btnsByClassName = $(".btn_green");
// By tagName
var $btnsByTagName = $("a");
/* This part is not part of the question, it is just to show that
these references are working */
$btnsByTagName.on('click', aTonOfStuff);
function aTonOfStuff() {
btnByClassName.style.backgroundColor = "black";
btnByTagName.style.color = "lime";
for (let i = 0; i < btnsByClassName1.length; i++) {
btnsByClassName1[i].style.fontSize = "40px";
btnsByClassName2[i].style.fontVariant = "small-caps";
}
btnsByClassNameA.style.backgroundColor = "#0E0";
btnsByClassNameB.style.color = "#000";
btnsByTagName1.style.lineHeight = "2";
btnsByTagName2.style.textDecoration = "overline";
$btnsByClassName.fadeOut("slow");
$btnsByTagName.fadeIn("slow");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click any link.</p>
<a class="btn_green" href="#/">First Green Button Anchor Link</a>
<a class="btn_green" href="#/">Second Green Button Ancor Link</a>
Something like $('a.btn_green') would "get" that <a> element but it is not guaranteed to get it uniquely. You may need to use something like the :nth-child pseudo-selector to do this if you cannot modify the source. Without more context it is impossible to say what a selector would be that would uniquely retrieve either the <a> or the <span> element.
Here is a jQuery tutorial and here is a CSS selector reference, just in case you need them.
Edit
One weird thing happening on the page is $ no longer seems to be bound to jQuery. They must be loading something which uses $ after jQuery which is causing selectors like $('a.btn_green') to return null. You can replace $ with jQuery instead.
I tried the using jQuery('.btn_green_white_innerfade.btn_medium') to find the element, but it looks like there are three elements on the page which share that selector. So I looked further up in the source and found that the button I think you want is within a div with the id market_buyorder_info. This led me to the following code to get the element uniquely:
jQuery('#market_buyorder_info').find('.btn_green_white_innerfade.btn_medium')
And this code to trigger a click in the console:
jQuery('#market_buyorder_info').find('.btn_green_white_innerfade.btn_medium').click()

How to swap placement of two elements, including their classes/ids with onclick?

I'm trying to switch the positions of two divs with an onclick event.
The divs have the same basic format (width, height), but an additional class and id change the way they look.
So, I have two functions that successfully change the id and class names, but there is no visual change.
Here they are:
function whenClickedFilled(){
console.log("filled");
this.firstElementChild.id = "empty";
this.firstElementChild.className = "puzzlepiece emptyDivClass";
}
function whenClickedEmpty(){
console.log("empty");
this.firstElementChild.id = "filled";
this.firstElementChild.className = "puzzlepiece";
}
I'd like to know what the best way is to alternate between classes/ids onclick.
Here is my js fiddle.
I think what you're really looking to do is not swaping the class and id, but swap the elements themselves. This will make sure the numbers contained within the div's is also transfer with the swap.
You still need to implement the logic checks to see if the element should be able to swap with the empty block and there looks like theres a bug when you click empty space itself. But, this should get you on the right track. I recommend placing a debugger statement to step through the code with dev tools open. It will help understand whats taking place. Good luck.
function whenClickedFilled(){
console.log("filled");
//Get the div element and parent
//Then determine the parent of the empty div
var clickedDiv = this.firstChild; //this refers to the TD clicked, get the child div element
var clickedDivParent = this; //this is TD
var emptyDivParent = emptyDiv.parentElement; //stored the empty div reference into a global, retrieve the parent as this could change
//Remove the empty and clicked div's from their container
emptyDivParent.removeChild(emptyDiv)
clickedDivParent.removeChild(clickedDiv);
//Add the elements back to the containers but swapped
clickedDivParent.appendChild(emptyDiv);
emptyDivParent.appendChild(clickedDiv);
}
http://jsfiddle.net/tWrD2/
I'm trying to switch the positions of two divs with an onclick event
If you want to swap two adjacent nodes, you can do something as simple as:
function swapAdjacent(el0, el1) {
el0.parentNode.insertBefore(el1, el0);
}
If you want to swap any two elements in the DOM, you can do something like:
// Swap the postion in the DOM of el0 and el1
function swapElements(el0, el1) {
// Create a temp node that can replace el0
var tmp = el0.cloneNode(false);
// Replace el0 with tmp
el0.parentNode.replaceChild(tmp, el0);
// Replace el1 with el0
el1.parentNode.replaceChild(el0, el1);
// Replace temp node with el1
tmp.parentNode.replaceChild(el1, tmp);
}
and some test markup:
<div id="d0">div 0</div>
<div id="d1">div 1</div>
<button onclick="
swapElements(document.getElementById('d0'), document.getElementById('d1'));
">Swap d0, d1</button>
<button onclick="
swapAdjacent(document.getElementById('d0'), document.getElementById('d1'));
">Swap adjacent</button>
Of course the two elements to swap must be consistent with the surrounding elements, e.g. you can't swap an option element with a div and expect everything to work, but you can probably swap a span with a div.
If you want to swap elements by clicking on one or the other:
<div id="d0" onclick="swapElements(this, document.getElementById('d1'))">div 0</div>
<div id="d1" onclick="swapElements(this, document.getElementById('d0'))">div 1</div>
I found a nice solution provided by fuell when I was searching fo an actual html swap:
<div id="div_1">THIS IS DIV 1</div>
<div id="div_2">THIS IS DIV 2</div>
Go Swap!
$(document).ready(function() {
$(".go-swap").click(function() {
$("#div_1").removeAttr("style");
$("#div_2").removeAttr("style");
var tmp = $("#div_1").html();
$("#div_1").empty().append($("#div_2").html());
$("#div_2").empty().append(tmp);
});
});

How can I identify every element in the DOM and the order of elements?

I want to be able to refer to any element within an HTML DOM and also know what order the elements appear in. I'm hoping elements in the DOM get indexed somewhere from 0 to <number-of-elements-minus-1> so that I can identify specific elements and, separately, list those elements in the order they appear within the HTML.
For example, in this HTML, the elements would be numbered from 0 for the html element, to 9 for the second p element:
<html lang="en-US">
<head>
<title>Element 2. Page title</title>
</head>
<body>
<h1 id="mainHead">Element 4. How to uniquely identify/order DOM elements</h1>
<div id="boxedContent">
<p class="smallText">Element 6. I want to be able to <span class="stress">7. uniquely</span> identify each element and <i>8. also</i> determine the order in which elements appear, reading from top to bottom through the HTML.</p>
</div>
<p>Element 9</p>
</body>
</html>
I want a JavaScript/jQuery way of specifying, for example, the title element, first p element and the span. The HTML pages I'll be working with aren't mine, but if there's a whole-DOM element index that I can access I could get to these 3 elements using those index refs - i.e.
title: 2
first p: 6
span: 7
The index numbers would allow me to list the elements in order.
Is this possible? How do I do it?
A better option would be to use node.compareDocumentPosition(node) (no jQuery needed)
see: https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition
Given a list of nodes you can sort them this way:
nodes.sort((a, b) =>
a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1
);
You could do something like this:
var elems = document.getElementsByTagName('*');
This will create an array-like object of all DOM element.
Then, there are many ways you can get the index of a specific element in that array-like object.
You could do this:
var indexOfTitle = elems.indexOf(document.getElementsByTagName('TITLE'));
Or, you can create a for loop which loops through all the elements in the elems variable, and uses a property like tagName to find it, etc.

addEventListener will not attach a listener to the element

/***************************************************** *
* Function: renderTodos
* Builds a list of todo items from an array
* rebuilds list each time new item is added to array
****************************************************** */
function renderTodos(arr) {
// erases all previous content
uList.innerHTML = '';
for ( var i = 0; i < tdArray.length; i++ ) {
// create a link element
var remex = document.createElement('span');
//link element didn't work so try a button
//var remex = document.createElement('input');
//remex.setAttribute('type','button');
remex.setAttribute('class', 'deletex');
remex.innerHTML="X";
// set attribute index and value
remex.setAttribute('index', i);
remex.addEventListener('click',removeTodo);
console.dir(remex);
// create <li> element
var li_element = document.createElement('li');
li_element.style.lineHeight = "20pt";
li_element.appendChild(remex);
li_element.innerHTML += tdArray[i];
// add item to list
uList.appendChild(li_element);
inField.value = '';
}
} // /renderTodos
This function builds a list based on text field inputs. Each time the the "add item" button is clicked, the event calls this function to add the item to the list. Everything works beautifully UNTIL I try to add the eventListener to the "x" that is appended to the li element prior to the list item text. The idea is that the "x" is clickable, and onClick it removes the list item entry from the list. But I have tried 6 ways to Sunday to attach an eventListener to the "x" object and nothing works. I have tried attaching the event listener to a span object, and a button object; I have moved "remex.addEventListener..." all around in the function, after it has been rendered, before it gets rendered, etc.; I have eliminated the CSS; I have tried changing the addEventListener to onClick; I have tried this code on our own Apache server, I have moved it to jsbin.com in hopes that some server setting was getting in my way; and probably a few more things I can't remember in the long list of things I have tried. As you see, I have tried it as a button and as a span, hence the commented code.
In short, no matter what I try, the eventListener will NOT attach to the "x". Any ideas? Do you need to see more of the code?
This line overrides the attached eventlistener:
li_element.innerHTML += tdArray[i];
Setting innerHTML replaces all the original elements within li_element. += is just a shortcut to li_element.innerHTML = li_element.innerHTML + tdArray[i];
If tdArray[i] contains just some text, you can add its content like this:
li_element.appendChild(document.createTextNode(tdArray[i]));
If tdArray[i] contains elements, you could append a wrapper element, and then set the innerHTML of the wrapper.

Categories

Resources