Link change in textbox - javascript

I am trying to create a script where a user clicks on the link type he wants and it opens it up in a small textfield below based on which he clicks.
For example
How can i create something like this where the user clicks on the link he wishes and it will change that textfield on click to which he desires?

Assuming the following mark-up style:
<ul>
<li><a class="linkInsert" href="http://www.example.com/article/">Link (email & blogs)</a></li>
</ul>
<input id="linkText" />​
Then you can use plain JavaScript:
var links = document.getElementsByTagName('a'),
textInput = document.getElementById('linkText'),
linkInserts = [];
for (var i = 0, len = links.length; i < len; i++) {
if (links[i].className == 'linkInsert') {
linkInserts.push(links[i]);
}
}
for (var i = 0, len = linkInserts.length; i < len; i++) {
linkInserts[i].onclick = function(e) {
e.preventDefault();
textInput.value = this.parentNode.innerHTML;
};
}​
JS Fiddle demo.
Or, with jQuery:
$('a.linkInsert').click(
function(e){
e.preventDefault();
$('#linkText').val($(this).parent().html());
});​​​​​​​​​​​​​​​​​​
JS Fiddle demo.
Changed the above HTML to the following, in order to avoid redundant attributes in the pasted HTML and then having to filter them back out, so now targeting the parent li element:
<ul>
<li class="linkInsert">Link (email & blogs)</li>
</ul>
<input id="linkText" />​
jQuery:
$('li.linkInsert a').click(
function(e){
e.preventDefault();
$('#linkText').val($(this).parent().html());
});​
JS Fiddle demo.
And the plain-JavaScript version updated to use the amended HTML:
var listElems = document.getElementsByTagName('li'),
textInput = document.getElementById('linkText'),
linkInserts = [];
for (var i = 0, len = listElems.length; i < len; i++) {
if (listElems[i].className == 'linkInsert') {
linkInserts.push(listElems[0].getElementsByTagName('a')[0]);
}
}
for (var i = 0, len = linkInserts.length; i < len; i++) {
linkInserts[i].onclick = function(e) {
e.preventDefault();
textInput.value = this.parentNode.innerHTML;
};
}​
JS Fiddle demo.
And using a slightly more up-to-date approach, with addEventListener():
function showHTML(evt){
evt.preventDefault();
var textInput = document.getElementById('linkText'),
target = evt.target,
targetTag = target.tagName.toLowerCase();
if (targetTag == 'a'){
textInput.value = target.parentNode.innerHTML;
}
else if (targetTag == 'li'){
textInput.value = target.innerHTML;
}
}
document
.getElementsByTagName('ul')[0]
.addEventListener('click',function(evt) { showHTML(evt) },false);
JS Fiddle demo.
And, finally, a version that seems compatible with ancient 'legacy' Internet Explorer (tested on IE 8, WinXP and IE 9, Win7):
function showHTML(evt) {
var evt = evt || event;
if (evt.preventDefault){
evt.preventDefault();
}
else {
event.returnValue = false;
}
var textInput = document.getElementById('linkText'),
target = evt.target ? evt.target : evt.srcElement,
targetTag = target.tagName.toLowerCase();
if (targetTag == 'a') {
textInput.value = target.parentNode.innerHTML;
}
else if (targetTag == 'li') {
textInput.value = target.innerHTML;
}
}
if (window.addEventListener) {
document.getElementsByTagName('ul')[0].addEventListener('click', function(evt) {
showHTML(evt)
}, false);
}
else if (window.attachEvent) {
document.getElementsByTagName('ul')[0].attachEvent('onclick', showHTML);
}​
JS Fiddle demo.
References:
addEventListener().
attachEvent().
event.preventDefault().
event.returnValue (an explanation, of sorts, discovered via Google, here on Stack Overflow).
getElementById().
getElementsByTagName().
push().

Make the links go nowhere, e.g #, give them an id, listen to click on thees with jquery or Use the onclick html attribute, select the area and set the clicked link text :-)

Related

How do I auto click an options drop down?

Here is the code that I have. It does select the option, but it does not click on it. I need it to click on the option or it will not work with the rest of my script. Any way of actually simulating a click?
//Country
function setOption(selectElement, value) {
var options = selectElement.options;
for (var i = 0, optionsLength = options.length; i < optionsLength; i++) {
if (options[i].value == value) {
selectElement.selectedIndex = i;
return true;
}
}
return false;
}
setOption(document.getElementById('billCountry'), Co);
//State
function setOption(selectElement, value) {
var options = selectElement.options;
for (var i = 0, optionsLength = options.length; i < optionsLength; i++) {
if (options[i].value == value) {
selectElement.selectedIndex = i;
return true;
}
}
return false;
}
setOption(document.getElementById('billState'), Sa);
Thank you for the help.
Sounds like the problem is in the rest of your script and you may want to consider changing it to not rely on a click. Consider using a "change" event. If you really need to fire a click event something like this should do it:
var element = document.getElementById('foo');
var e = document.createEvent('MouseEvents');
e.initEvent('click', true, true);
element.dispatchEvent(e);

javascript menu, How to close when mouse outside of div?

this is my first pure JavaScript script as you can probably tell, by the length of it! I'm at a loss to workout how i can get the child links which are in a div with a class called 'menu' to close when i leave that div.
I've tried to write an If argument to set it to close when i leave the 'A' and also a 'DIV' and that doesn't seem to work?
Any help would be much appreciated and sorry for the overly long code!
Please no Jquery for now, thanks!
<script>
// Variables
var getFirstMenu = document.getElementsByTagName('div');
// Use selectors
var getMenuClasses = document.getElementsByClassName('menu');
// Hide drop down menus
for(var i=0; i < getFirstMenu.length; i++){
getFirstMenu[i].style.visibility = 'hidden';
}
// =============================
// Show Menu on mouseover
function showDropdown(e){
var el = e.target;
if(el.nodeName == 'A'){
for(var i = 0; i < getMenuClasses.length; i++) {
if(el == getMenuClasses[0]){
getFirstMenu[0].style.visibility = 'visible';
}else if(el == getMenuClasses[1]) {
getFirstMenu[1].style.visibility = 'visible';
}else if(el == getMenuClasses[2]){
getFirstMenu[2].style.visibility = 'visible';
}
}
}
}
var getMainMenu = document.getElementById('menu');
getMainMenu.addEventListener('mouseover', function(e){
showDropdown(e);
},false);
// =============================
// Hide Menu on mouseout
function mouseOutMenu(e){
var el = e.target;
if(el.nodeName == 'DIV')
for(var i = 0; i < getFirstMenu.length; i++){
getFirstMenu[i].style.visibility = 'hidden';
}
}
getMainMenu.addEventListener('mouseout', function(e){
mouseOutMenu(e);
}, false);
Add a Handler to the document-object
document.addEventHandler('mouseover', function(){
// close it
}, false);
Or when this is about to hide a submenu: Add the handler to the menu which then hides the menu on mouseover
Look Demo
Code :
// Variables
var getFirstMenu = document.getElementsByTagName('div');
// Use selectors
var getMenuClasses = document.getElementsByClassName('menu');
// Hide drop down menus
for(var i=0; i < getFirstMenu.length; i++){
getFirstMenu[i].style.visibility = 'hidden';
}
// =============================
// Show Menu on mouseover
function showDropdown(e){
var el = e.target;
if(el.nodeName == 'A'){
for(var i = 0; i < getMenuClasses.length; i++) {
if(el == getMenuClasses[0]){
getFirstMenu[0].style.visibility = 'visible';
}else if(el == getMenuClasses[1]) {
getFirstMenu[1].style.visibility = 'visible';
}else if(el == getMenuClasses[2]){
getFirstMenu[2].style.visibility = 'visible';
}
}
}
}
var getMainMenu = document.getElementById('menu');
getMainMenu.addEventListener('mouseover', function(e){
showDropdown(e);
},false);
// =============================
// Hide Menu on mouseout
function mouseOutMenu(e){
var el = e.target;
//if(el.nodeName == 'A')
for(var i = 0; i < getFirstMenu.length; i++){
getFirstMenu[i].style.visibility = 'hidden';
}
}
for(var i = 0; i < document.getElementsByTagName('div').length; i++){
document.getElementsByTagName('div')[i].addEventListener('mouseout', function(e){
mouseOutMenu(e);
}, false);
}

Unable to define a click event on a href tag

I am trying to write a click event for an anchor tag in my tampermonkey script.
var contentTag = document.getElementsByTagName("pre")[0];
var fileContents = contentTag.innerHTML;
contentTag.innerHTML = "";
var lines = fileContents.split("\n");
window.alert("Number of lines:"+lines.length);
for(var i=0; i<20; i++) {
if(i!==15)
contentTag.innerHTML+=(lines[i]+"<br>");
else {
contentTag.innerHTML+=("<a id=link1>Click me</a>");
var link = document.getElementById('link1');
link.addEventListener("click", function() {
window.alert('I am clicked');
}, false);
}
}
The alert message never gets triggered when I click on the link in the page dispalyed, even though I have a a click event listener defined. What am I doing wrong here?
It's the way you're adding HTML, you're reappending the link when you do this in the next iteration.
link.innerHTML += something
So the event handler is lost, and you can actually prove that by adding the event handler to the last element instead.
If you do it the proper way, creating elements and appending them, it works fine
var contentTag = document.getElementsByTagName("pre")[0];
var fileContents = contentTag.innerHTML;
contentTag.innerHTML = "";
var lines = fileContents.split("\n");
for (var i = 0; i < 20; i++) {
if (i !== 15) {
var txt = document.createTextNode(lines[i] || ''),
br = document.createElement('br');
contentTag.appendChild(txt);
contentTag.appendChild(br);
} else {
var link = document.createElement('a');
link.id = 'link1';
link.innerHTML = 'Click me';
link.addEventListener("click", function () {
alert('clicked')
}, false);
contentTag.appendChild(link)
}
}
FIDDLE
Shoud be contentTag.innerHTML+=("<a id='link1'>Click me</a>");
Try this:
<script>
var contentTag = document.getElementsByTagName("pre")[0];
var fileContents = contentTag.innerHTML;
contentTag.innerHTML = "";
var lines = fileContents.split("\n");
window.alert("Number of lines:"+lines.length);
for(var i=0; i<20; i++) {
if(i!==15)
contentTag.innerHTML+=(lines[i]+"<br>");
else {
contentTag.innerHTML+=("<a id=link"+i+">Click me</a>");
var link = document.getElementById('link'+i);
var att=document.createAttribute('onclick');
att.value="alert('Clicked !')";
link.setAttributeNode(att);
}
}
</script>
Demo: http://jsfiddle.net/TmJ38/

Add class active when clicking menu link with JAVASCRIPT

HTML
<div id="top" class="shadow">
<ul class="gprc">
<li>Home</li>
<li>Text1</li>
<li>Text2</li>
<li>Text3</li>
<li>Text4</li>
</ul>
Javascript
window.onload = setActive;
function setActive() {
aObj = document.getElementById('top').getElementsByTagName('a');
var found = false;
for (i = 0; i < aObj.length; i++) {
if (document.location.href.indexOf(aObj[i].href) >= 0) {
aObj[i].className = 'active';
found = true;
}
}
if (!found) {
aObj[0].className = 'active';
}
}
The problem is that the menu home link remains selected or active all the time even if i click on other links and I would like to make it not selected on loading of the page and also to remain non-selected while other link that i clicked and i am on the specific landing page remains selected. Please only Javascript no JQUERY.
Try this:
window.onload = setActive;
function setActive() {
var aObj = document.getElementById('top').getElementsByTagName('a');
var found = false;
for(var i=aObj.length-1; i>=1 && !found; i--) {
if(document.location.href.indexOf(aObj[i].href)>=0) {
aObj[i].className='active';
found = true;
}
}
//if you never want home selected remove the next
if(!found && document.location.href.replace(/\/$/, "") == aObj[0].href.replace(/\/$/, ""))
aObj[0].className = 'active';
}
With this way you start at the end of the list, and when you find a coincidence it stop the search of an active link.
I hope it helps you
function setActive() {
var top = document.getElementById('top'),
aObj = top.getElementsByTagName('a'),
href = document.location.href,
found = false;
for (var i = 0; i < aObj.length || !found; i++) {
if (href.indexOf(aObj[i].href) >= 0) {
aObj[i].className = 'active';
found = true;
}
}
if (!found) {
aObj[0].className = 'active';
}
//Listen for link clicks
function listener(e) {
if(e.target.tagName === "A") {
for (var i = 0; i<aObj.length; i++) {//remove previous class
aObj[i].className = "";
}
e.target.className = "active";
}
}
if(top.addEventListener) {
top.addEventListener(listener);
} else if(top.attachEvent) {
top.attachEvent(listener);
}
}
You're going to need to listen to the click event so you can determine if one of your links is pressed. I'm going to do this using some simple delegation

How to stop event when user clicks inside certain divs using JavaScript

I want this code to check if the user has clicked inside the open box and if so then it will keep it open, also if the user clicks outside the box it will close.
http://jsfiddle.net/MTJa5/26/
var boxes = function(){
var divClicks = document.getElementsByClassName("clickToShow");
for(i=0; i < divClicks.length; i++){
var click = divClicks[i];
var clickEvent = function(){
click.addEventListener("click", function(e){
var currentClass= this.getElementsByTagName('div')[0].className;
var divs = document.getElementsByClassName('openedBox');
for(var i = 0; i < divs.length; i++){
divs[i].setAttribute("class", "closedBox");
}
if(currentClass === "openedBox"){
this.childNodes[3].setAttribute("class", "closedBox");
} else {
this.childNodes[3].setAttribute("class", "openedBox");
}
},false);
}();
}
}();
Instead of binding several event listeners, you can also bind just one click event, and use the event.target property to check where you've clicked.
The updated code is less comples, and easier to maintain.
Demo: http://jsfiddle.net/MTJa5/28/
var hellos = function() {
function closeAllButThisBox(targ) {
var allBoxes = document.getElementsByClassName('openedBox');
for (var i=allBoxes.length-1; i>=0; i--) {
if (allBoxes[i] !== targ) {
allBoxes[i].className = 'closedBox';
}
}
}
window.addEventListener('click', function(ev) {
var targ = ev.target;
// Traverse the tree, until you hit the desired / root element
while (targ && targ !== document.documentElement) {
if (targ.className.indexOf('openedBox') !== -1) {
closeAllButThisBox(targ);
// Do nothing when clicking inside an opened box
return;
}
// This will open boxes, if closed, when clicking at the <p>
if (targ.tagName.toLowerCase() === 'p' && targ.parentNode.className.indexOf('clickToShow') !== -1) {
closeAllButThisBox(targ.parentNode);
targ.parentNode.getElementsByTagName('div')[0].className = 'openedBox';
return;
}
targ = targ.parentNode;
}
// At this point, the click is not at the right place.
// Close all boxes by removing the closedBox class names
var boxes = document.getElementsByClassName('openedBox');
for (var i=boxes.length-1; i>=0; i--) {
boxes[i].className = 'closedBox';
}
}, false);
}();

Categories

Resources