Why can't I update an input element inside click event? - javascript

Why does the input element not get updated?
function route() {
let textfield = {
inputEl: document.querySelector('#textfield'),
setValue: function(str) {
this.inputEl.value = str;
}
};
textfield.inputEl.addEventListener('click', function(event) {
document.body.innerHTML += '<button id="select">Select</button>';
owner(textfield);
});
}
function owner(controller) {
document.querySelector('#select').addEventListener('click', function(event) {
controller.setValue("Hello Universe!");
});
}
route();
I know how to go around this problem but i prefer to use controller.setValue() to update the input.

UPDATED
I have updated the code below - hopefully this is closer to what you are trying to achieve.
I needed to add a container where to place the button (instead of adding it to the body) - so added a wrapper container like this:
<div id="container">
<input type="text" id="textfield" />
</div>
Then, we can append the button to it as a child, like this:
document.getElementById('container').appendChild(btn);
See updated code below
function route() {
let textfield = {
inputEl: document.querySelector('#textfield'),
setValue: function(str) {
this.inputEl.value = str;
}
};
textfield.inputEl.addEventListener('click', function(event) {
// add the button if it's not already in there
if(document.getElementById('select')){
return;
}
let btn = document.createElement('button');
btn.id = 'select';
btn.innerHTML = 'Select';
document.getElementById('container').appendChild(btn);
owner(textfield);
});
}
function owner(controller) {
document.getElementById('select').addEventListener('click', function(event) {
controller.setValue("Hello Universe!");
});
}
route();
<div id="container">
<input type="text" id="textfield" />
</div>

Related

src not changing on else if part of if/else statement

I have created a function which is used in an event listener function so when the user clicks the left arrow icon on the webpage, a different character image is displayed. The first click works fine and the image is changed, however on the second click, nothing happens. I can't figure out why as from what I can see, the condition of the 'else if' of the statement is true so therefore the src code should change accordingly and change the image.
There are no error messages in the console.
Here is the Event listener:
document.querySelector(".left").addEventListener("click", () => {
leftArrow();
});
Here is the leftArrow function:
leftArrow: () => {
if (document.querySelector(DOMStrings.characterImg).src = characters[0]) {
document.querySelector(DOMStrings.characterImg).classList.add("boris");
document.querySelector(DOMStrings.characterImg).src = characters[1];
const el = document.querySelector(DOMStrings.characterImg);
console.log(el);
} else if (document.querySelector(DOMStrings.characterImg).src = characters[1]) {
document.querySelector(DOMStrings.characterImg).classList.remove("boris");
document.querySelector(DOMStrings.characterImg).src = characters[0];
const el = document.querySelector(DOMStrings.characterImg);
console.log(el);
}
Here is where the images are stored:
const characters = ["Resources/Images/trump.png", "Resources/Images/boris.png"];
Here is where the DOM strings are stored:
const DOMstrings = {
characterImg: ".character-img"
}
Lastly, here is the relevant html:
<div class="character-select">
<ion-icon class="left" name="arrow-dropleft-circle"></ion-icon>
<ion-icon class="right" name="arrow-dropright-circle"></ion-icon>
<img class="character-img" src="Resources/Images/trump.png">
</div>
function myFunction() {
document.getElementById("myImg").src = "https://www.w3schools.com/jsref/hackanm.gif";
}
function myFunctionbygeneric(){
document.querySelector(".test").src = "https://www.w3schools.com/jsref/hackanm.gif";
}
function myFunctionbygenericid(){
document.querySelector("#myImg").src = "https://www.w3schools.com/jsref/compman.gif";
}
<img id="myImg" class="test" src="https://www.w3schools.com/jsref/compman.gif" width="107" height="98">
<button onclick="myFunction()">click here</button>
<button onclick="myFunctionbygenericid()">Query selector by id</button>
<button onclick="myFunctionbygeneric()">Query selector</button>
Use can use like this
let myImage = document.querySelector('img');
myImage.onclick = function() {
let mySrc = myImage.getAttribute('src');
if(mySrc === 'https://www.w3schools.com/jsref/compman.gif') {
myImage.setAttribute ('src','https://www.w3schools.com/jsref/hackanm.gif');
} else {
myImage.setAttribute ('src','https://www.w3schools.com/jsref/compman.gif');
}
}
<img src="https://www.w3schools.com/jsref/hackanm.gif" />

Unable to generate a mouse click event inside a input box using javascript/jquery

I am unable to generate a mouse click event inside an input box. I am trying to simulate a user doing a mouse click.
I am trying to use the Chrome console to run these and none is working.
I have tried using the below code.
HTML Input Box:
<input type="email" name="email" class="auth0-lock-input" placeholder="yours#example.com"
autocomplete="off" autocapitalize="off" aria-label="Email" aria-invalid="false"
value="">
Javascript:
document.getElementsByClassName('auth0-lock-input')[0].click();
Or
document.getElementsByClassName('auth0-lock-input')[0].mouseenter();
Or
let element= document.getElementsByName('email');
for (elt of element) {
elt.mouseenter();
}
`````````````````React Listener`````````````````````````
trapBubbledEvent: function (topLevelType, handlerBaseName, element) {
if (!element) {
return null;
}
return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType));
trapCapturedEvent: function (topLevelType, handlerBaseName, element) {
if (!element) {
return null;
}
return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType));
},
monitorScrollValue: function (refresh) {
var callback = scrollValueMonitor.bind(null, refresh);
EventListener.listen(window, 'scroll', callback);
},
dispatchEvent: function (topLevelType, nativeEvent) {
if (!ReactEventListener._enabled) {
return;
}
var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent);
try {
ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping);
} finally {
TopLevelCallbackBookKeeping.release(bookKeeping);
}
};
module.exports = ReactEventListener;
`````````````````````````````````
Actually I think that your code is working, but the click() on a input doesnt do any visual effect.
To test it, run:
let input = document.getElementsByClassName('auth0-lock-input')[0]
input.addEventListener('click', () => alert('Clicked') )

Javascript - use callback with addEventListener for "remove all" button

I'm adding a "remove all" button to my chrome extension which as the name suggests should serve to remove all saved links.
The button works only after I have performed some other action first (adding a link, removing a link etc) but of course, I want it to work right away.
I have read that this may be due to the code being asynchronous so I tried introducing a callback function with the help of this question: Add callback to .addEventListener however, it's still performing the same way it did before so maybe that wasn't the issue after all, or I may have read the other question wrong. I appreciate any tips so thank you in advance. I will try to figure it out myself in the meantime.
var urlList = [];
var i = 0;
document.addEventListener('DOMContentLoaded', function() {
getUrlListAndRestoreInDom();
// event listener for the button inside popup window
document.getElementById('save').addEventListener('click', addLink);
});
function addLink() {
var url = document.getElementById("saveLink").value;
addUrlToListAndSave(url);
addUrlToDom(url);
}
function getUrlListAndRestoreInDom() {
chrome.storage.local.get({
urlList: []
}, function(data) {
urlList = data.urlList;
urlList.forEach(function(url) {
addUrlToDom(url);
});
});
}
function addUrlToDom(url) {
// change the text message
document.getElementById("saved-pages").innerHTML = "<h2>Saved pages</h2>";
var newEntry = document.createElement('li');
var newLink = document.createElement('a');
var removeButton = document.createElement('button');
removeButton.textContent = "Remove";
removeButton.type = "button";
removeButton.className = "remove";
removeButton.addEventListener("click", function() {
var anchor = this.previousElementSibling;
var url = anchor.getAttribute("href");
removeUrlAndSave(url);
this.parentNode.remove();
});
newLink.textContent = url;
newLink.setAttribute('href', url);
newLink.setAttribute('target', '_blank');
newEntry.appendChild(newLink);
newEntry.appendChild(removeButton);
newEntry.className = "listItem";
document.getElementById("list").appendChild(newEntry);
}
function removeUrlAndSave(url) {
var index = urlList.indexOf(url);
if (index != -1) {
urlList.splice(index, 1);
saveUrlList();
}
}
function addUrlToListAndSave(url) {
urlList.push(url);
saveUrlList();
//}
}
function saveUrlList(callback) {
chrome.storage.local.set({
urlList
// }, function() {
// if (typeof callback === 'function') {
// //If there was no callback provided, don't try to call it.
// callback();
// }
// });
});
function removeMe(i) {
var fullList = documents.getElementsByClassName('listItem');
listItem[i].parentNode.removeChild(listItem[i]);
}
function removeAll() {
var removeList = document.getElementsByClassName("listItem");
while (removeList[0]) {
removeList[0].parentNode.removeChild(removeList[0]);
};
}
function registerElement(callback) {
var element = document.getElementById("remove-all-button");
element.addEventListener("click", callback);
}
registerElement(removeAll);
#list {
min-height: 360px;
max-height: 360px;
width: 300px;
margin: auto;
overflow: scroll;
}
<head>
<script type="text/javascript" src="popup.js"></script>
<link rel="stylesheet" href="popup.css">
</head>
<body>
<div>
<span id="hot-button">Hot Drops</span>
<li id="removeAll">
<button id="remove-all-button"> Remove All</button>
</li>
<span id="saved-pages"></span>
<div>
<ul id="list"></ul>
</div>
</div>
<input type="button" id="save" value="Add">
<input type="text" id="saveLink" name="member" value=""><br/>
<span id="settings-button">Settings</span>
</body>
</html>
there you go
jsfiddle
had to write this line to post link
http://jsfiddle.net/1w69bo8k/ - you made a lot of mistakes, where you put certain code, to using variables I never saw them defined anywhere in code
(you keep editing the question, I went from this fiddle you provided)
change back to your getUrlListAndRestoreInDom function, deleted the storage code
you update the storage and the urlList manually, rather do it after the update of local is successful

Handling focus on a toggle button

I am trying to keep the focus on the toggle button after it gets pressed.
Right now, when I click on the button, the focus jumps to the top of the page. I am not sure what I am doing wrong.
Here is the code:
HTML
<button ng-if=“test” ng-click=“deactivate()">Deactivate</button>
<button ng-if=“!test” ng-click="activate()”>Activate </button>
JS
$scope.activate = function () {
var activateButton = document.activeElement;
if ($scope.some.length) {
$scope.enableSome($scope.some, true);
}
activateButton.onclick = function () {
activateButton.focus();
};
};
$scope.deactivate = function () {
var activateButton = document.activeElement;
if ($scope.some.length) {
$scope.enableSome($scope.some, false);
}
activateButton.onclick = function () {
activateButton.focus();
};
};
You actually have two buttons that are added/removed from the DOM based on the ng-if condition (documentation).
Your button is not getting focused because the activate button is getting removed while the deactivate button is added, and vice versa.
We can refactor the two buttons into one using a toggleActivation() method.
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.test = false;
$scope.some = [1, 2, 3];
$scope.enableSome = function(some, activate) {
//Do whatever
console.log('enableSome called with activate = ' + activate);
}
$scope.toggleActivation = function() {
//Toggle the state
$scope.test = !$scope.test;
if ($scope.some.length) {
$scope.enableSome($scope.some, $scope.test);
}
//The button is still focused!
console.log('Focused element: ', document.activeElement);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<button ng-click="toggleActivation()">
{{test ? "Deactivate" : "Activate"}}
</button>
</div>

Custom styled checkbox not working properly

Currently I'm using multiple blocks of the following code as my custom styled checkbox:
<div class="row-fluid">
<div class="span12 card card-even">
<div>
<h3><label class="checkbox">
<i class="icon-check-empty"></i>
<input type="checkbox" value="1" />
</label></h3>
</div>
</div>
</div>
The JS:
jQuery.fn.extend({
shinyCheckbox: function() {
var setIcon;
setIcon = function($el) {
var checkbox, iclass;
checkbox = $el.find("input[type=checkbox]");
iclass = "";
if (checkbox.is(":checked")) {
iclass = "icon-ok";
} else {
iclass = "icon-check-empty";
}
return $el.find("i[class^=icon-]").removeClass("icon-check").removeClass("icon-check-empty").addClass(iclass);
};
this.find("input[type=checkbox]").change(function() {
return setIcon($(this).parents("label.checkbox"));
});
return this.each(function(i, el) {
return setIcon($(el));
});
}
});
$(document).ready(function() {
return $("label.checkbox").shinyCheckbox();
});
Im able to achieve my requirement by styling the icon-check-empty & icon-check classes but when i click any checkbox only the first checkbox gets activated.
How can i use the this keyword to solve the issue such that the correct checkbox is activated?
This is the way I'd do it, based on your code:
jQuery.fn.extend({
shinyCheckbox: function () {
var setIcon = function ($el) {
var checkbox = $el.find("input[type=checkbox]"), checked = checkbox.is(':checked');
checkbox.val(+checked);
return $el.find("i[class^=icon-]").removeClass("icon-check-empty icon-ok").addClass(function () {
return checked ? "icon-ok" : "icon-check-empty";
});
};
this.find("input[type=checkbox]").on('change', function () {
return setIcon($(this).closest("label.checkbox"));
});
return this.each(function (i, el) {
return setIcon($(el));
});
}
});
$(document).ready(function () {
$("label.checkbox").shinyCheckbox();
});
The main issue was that you weren't removing the icon-ok class, only the icon-check class. I also cleaned the code up a little.
Here it is working: http://jsfiddle.net/W88fk/1/
you can try
jQuery.fn.extend({
shinyCheckbox: function() {
return this.each(function() {
var el=$(this),checkbox = el.find("input[type=checkbox]");
checkbox.change(function() {
var iclass = checkbox.is(":checked")?"icon-ok":"icon-check-empty";
el.find("i[class^=icon-]").removeClass().addClass(iclass);
var cval= checkbox.is(":checked")?0:1;
checkbox.val(cval);
});
});
}
});
$(document).ready(function() {
$("label.checkbox").shinyCheckbox();
});
toogle class and value http://jsfiddle.net/rWFMm/1/

Categories

Resources