Change icon with javascript - javascript

In my foray into web development I have found a new problem, I need to change the icon for another one when I click on it. I have an idea of a function in javascript that sends the id of the icon and with the obtain the element, after obtaining element I hope to change keyboard_arrow_up by keyboard_arrow_down. However that is the part that is not performed, how do I get the value keyboard_arrow_up?
function change(iconID) {
var item = document.getElementById(iconID);
if (item) {}
}
<i id="icon1" onclick="change('icon1')" class="material-icons">keyboard_arrow_up</i>

This is the temporary solution, I had to change the icons of google design material by the fontawesome icons. However, I will continue investigating.
function change (iconID){
if(document.getElementById(iconID).className=="fa fa-chevron-up"){
document.getElementById(iconID).className = "fa fa-chevron-down";
}else{
document.getElementById(iconID).className = "fa fa-chevron-up";
}
}
<i id="icon1" onclick="change('icon1')" class="fa fa-chevron-up" aria hidden="true">

Sounds like , you need this kind of function
function changeIcon(classname or id) {
$("i", this).toggleClass("icon-circle-arrow-up icon-circle-arrow-down");
}
Note : the icons in above solution are copied from internet , please use your desire icons in there.

Remember Icons are just CSS class, so the function should change the class for another on the javascript function.
function change(iconID) {
var element = document.getElementById(iconID);
if (element.classList.contains("keyboard_arrow_up")) {
element.classList.add("keyboard_arrow_down")
} else {
element.classList.add("keyboard_arrow_up")
}
}

You can change innerText as follows:
document.addEventListener("DOMContentLoaded", function() {
let change = document.querySelector("#icon");
change.addEventListener('click' ,function () {
let item = document.querySelector("#icon");
if(this.innerText == 'keyboard_arrow_down'){
item.innerText = "keyboard_arrow_up";
}else{
item.innerText = "keyboard_arrow_down";
}
})
});
and the html:
<i id="icon" class="material-icons">keyboard_arrow_up</i>

function change(iconID) {
var item = document.getElementById(iconID);
if (item) {}
}
<i id="icon1" onclick="change('icon1')" class="material-icons">keyboard_arrow_up</i>
snap pans

Related

Click to change image across multiple items

I'm trying to set up a javascript function that will take a down arrow image and swap it with an up arrow image when clicked. It worked when the image had an id, but because I have a couple menu items that uses the arrow image, I wanted to try to get it to work as a class name or just regular name, but I can't get the function to change the source of the image when it's not an id. Can anyone help?
Here is my current HTML markup:
<div class="header__links hide-for-mobile" >
<a id="subMenu" href="#">Features <img class="downArrow" src="/assets/images/icon-arrow-down.svg"></a>
Company
Careers
About
</div>
And here is my JS
const subMenu = document.querySelector('#subMenu');
subMenu.addEventListener('click', function() {
if(subMenu.classList.contains('subOpen')) {
subMenu.classList.remove('subOpen');
document.getElementsByClassName('downArrow').src="/assets/images/icon-arrow-down.svg";
}
else {
subMenu.classList.add('subOpen');
document.getElementsByClassName('downArrow').src="/assets/images/icon-arrow-up.svg";
}
})
Right now since your markup only contains a single element with the downArrow class you could update your code to:
const subMenu = document.querySelector('#subMenu');
subMenu.addEventListener('click', function() {
if(subMenu.classList.contains('subOpen')) {
subMenu.classList.remove('subOpen');
document.getElementsByClassName('downArrow')[0].src="/assets/images/icon-arrow-down.svg";
}
else {
subMenu.classList.add('subOpen');
document.getElementsByClassName('downArrow')[0].src="/assets/images/icon-arrow-up.svg";
}
})
But a better way to do this would be to loop through the results of the getELementsByClassName method. You could do that with something like:
const subMenu = document.querySelector('#subMenu');
subMenu.addEventListener('click', function() {
if(subMenu.classList.contains('subOpen')) {
subMenu.classList.remove('subOpen');
Array.from(document.getElementsByClassName("downArrow")).forEach(
function(element, index, array) {
element.src="/assets/images/icon-arrow-down.svg";
}
);
}
else {
subMenu.classList.add('subOpen');
Array.from(document.getElementsByClassName("downArrow")).forEach(
function(element, index, array) {
element.src="/assets/images/icon-arrow-up.svg";
}
);
}
})

Change class name of font-awesome when clicked

Here is the problem
This is my html code
<div id="bookmark">
<i class="far fa-bookmark"></i>
</div>
I want to change .far to .fas and vice versa in loop when clicked.
This is my updated javascript
function changeClass(elem) {
var i = elem.childNodes[1];
var c = i.classList;
console.log(i)
console.log(c)
// Change class
if (c.contains("far")) {
i.classList.remove("far");
i.classList.add("fas");
} else {
i.classList.remove("fas");
i.classList.add("far");
}
}
This is the screenshot of the console output in the browser when I click on the bookmark icon
Screenshot
When I pass the index value in the var c respectively, on i.classList[0] I get svg-inline--fa but I get undefined value in i.classList[3] instead of far. SO WHAT SHOULD I DO?
I hope this is what you are looking for (Demo: https://jsfiddle.net/hwv0oacL/8/)
HTML
<div id="bookmark" onclick="changeClass(this)">
<i class="far fa-bookmark"></i>
</div>
Javascript
changeClass(elem) {
var i = elem.childNodes[0].classList;
// Change class far to fas
if (i.includes("far")) {
i.classList.remove("far");
i.classList.add("fas");
}
// Get back to original state
if (i.includes("fas")) {
i.classList.remove("fas");
i.classList.add("far");
}
}
-------------------Updated--------------------------
Replace the above javascript with the one below. It will also work in loop like you want because we are getting element by this keyword.
JavaScript
function changeClass(elem) {
var i = elem.childNodes[1];
var c = i.classList;
// Change class
if (c.contains("far")) {
i.classList.remove("far");
i.classList.add("fas");
} else {
i.classList.remove("fas");
i.classList.add("far");
}
}
You can do it like below with jQuery:
$("#bookmark").find("i").removeClass("far");
$("#bookmark").find("i").addClass("fas");
assuming you want this to be done for single element and not for all the elements that are using .far class
add an id to the tag like id="i1" then you can add an event listener on that element. listening to the click event and once captured - toggle the class.
add the following just before the end of the body tag i.e. before </body>
<script>
document.getElementById('i1').addEventListener('click', (e) => {
e.target.classList.toggle('far');
e.target.classList.toggle('fas');
})
</script>

Click and toggle between two classes on an array (no JQuery)

I need to make a site where I can add something to a shoppingcart. I do not need to store any data, so just changing a class to 'addedInCart' is enough. This is what I have so far, but it's not working yet. I know all the classnames I got are coming back in an array. I just dont know how to change them if the button is clicked. I tried a lot with the addEventListener and the toggle, but I just started coding, not everything is clear for me yet. I am not alloud to use Jquery, only HTML and Javascript.
This is what I have in Javascript:
var buyMe = document.getElementsByClassName("materials-icon");
function shoppingcart() {
for(let i = 0; i < buyMe.length; i++){
buyMe[i].classList.toggle("addedInCart");
buyMe[i].addEventListener("click", toggleClass, false)
}
}
This is what my button looks like:
<button class="material-icons" onclick="shoppingcart()"></button>
Thank you for your time!
Use event delegation to be able to use one handler. Use a data-attribute to verify the button as being a button for adding to cart. Something like:
document.addEventListener("click", handle);
function handle(evt) {
const origin = evt.target;
if (origin.dataset.cartToggle) {
// ^ if element has attribute data-cart-toggle...
origin.classList.toggle("addedInCart");
// ^ ... toggle the class
}
};
.addedInCart {
color: red;
}
.addedInCart:after {
content: " (in cart, click to remove)";
}
<button class="material-icons" data-cart-toggle="1">buy</button>
<button class="material-icons" data-cart-toggle="1">buy</button>
<button class="material-icons" data-cart-toggle="1">buy</button>

Highlight single element in ng-repeat

following problem:
I am using ng-repeat to generate a list of items. If the user clicks on a special marker on my webpage above, the following function receives an event an scrolls down to the corresponding item. In addition to scrolling down I would like to highlight the item until the user moves the mouse again. My problem ist that do to this I need to manipulate the css class of one single element of my ng-repeat list. I thought it might be possible because every ng-repeat element gets its own local scope...but I don't find the solution.
Part of my directive:
//if a marker is clicked, the following code should bring the user to the corresponding item
$rootScope.$on("Scroll_to_product", function (event, args) {
product.gotoElement(args);
});
/*function which takes the class id of an html element as argument and brings
the user to the corresponding product*/
product.gotoElement = function (args) {
var elementID = 'product-' + args;
$location.hash(elementID);
// call $anchorScroll()
$anchorScroll();
}
Any help would be great,
Thanks, Hucho
I think this woking Plunker example may help you
Plunker link
$scope.idSelectedVote = null;
$scope.setSelected = function(idSelectedVote) {
$scope.idSelectedVote = idSelectedVote;
console.log(idSelectedVote);
}
.selected {
background-color: red;
}
<ul ng-repeat="vote in votes" ng-click="setSelected(vote.id)" ng-class="{selected : vote.id === idSelectedVote}">
</ul>
it almost broke my head, but finally was easy:
product.highlightFeature = function (args) {
var id = '#'+ 'feature-' + args;
var myEl = angular.element( document.querySelector( id ) );
myEl.addClass('feature-highlight');
};
It is easy and fast..; yet thanks for your help.
This might help others...
Best
Hucho

jquery append element and keep reference for removing it later

what is the correct method to append a div to dom, and keep a handle for manipulating that dom later ? and case removing it will the refrence be deleted also ? if not how can i ?
this is an example code of what i came out with, please let me know your opinon and if there is a better more solid method for doing this.
note that i keep reference in an array because many elements can manipulate element.
var layovers=[];
function ajaxMe($e){
//do some ajax call
var lay=layoverThis($e);
layovers[lay].remove(); //does this remove added element from dom ? does it unset layouvers[lay] too ?
}
function layoverThis($e){
var p=layover.push($('<div class="overlay" ><span><i class="fa fa-spinner fa-spin"/>loading</span></div>')) - 1;
$e.append(layover[p]);
return p;
}
nearest example i can think of is like opening a folder in windows Os.
when you open a folder: a new window opens to your desktop, while also there is a taskbar tab that is added linked to same window that was appended to your desktop, allowing system to manipulate window (close-restore minimize etc..), so how do i do this in javasript.
my question is how to make such behavior in a manner that is flexible and not hacky or memory wasteful.
You can use a psudoClass and an index - add the event to the delete element as you create the element in the DOM. OR have an onclick that removes the parent div that was appended..
So, you're code will look like:
function layoverThis($e){
var p=layover.push($('<div class="overlay" ><span><i class="fa fa-spinner fa- spin"/>loading</span> <span class="closeThis" onclick="$(this).parent().remove();" > Close </span></div>')) - 1;
$e.append(layover[p]);
return p;
}
Let me know if this works for you, i have a number of other solutions.
Update:
To facilitate the object to be selectable, I would use a psudoClass..
document.ready(function() {
addADiv($('#myParent'));
getArrayOfDivs().css('background-color', 'red');
doAjax(lastClicked);
});
function doAjax(ctrl)
{
}
var lastClicked = "";
$('.dynamicDivs').click(function() {
lastClicked = $(this);
});
function getArrayOfDivs() {
return $('.dynamicDivs');
}
function addADiv($where){
var uniqueIdentifier = $('.dynamicDivs').count() + 1;
$where.append($('<div class="overlay dynamicDivs ' + uniqueIdentifier + ' " ><span><i class="fa fa-spinner fa- spin"/>loading</span></div>'));
}

Categories

Resources