How to Change a Font Class Name Inside a Link With JQuery - javascript

I'm trying to change the font class name after clicking the link with Javascript and jQuery.
The button example:
<a class='pe-1' onclick='change(this, 24)'><i class='bx bx-bookmark'></i></a>
If I try this way below will change the class from the link instead of the class from the font...
Function example 1:
function change(button, id) {
var changeButton = $(button);
changeButton.removeClass("bx-bookmark").addClass("bxs-bookmark");
}
Unfortunately doing the basic way (like my example below) doesn't really work for me since is going to change the value from all posts instead of just that one post.
Function example 2:
function change(button, id) {
var changeButton = $(button);
$(".bx").removeClass("bx-bookmark").addClass("bxs-bookmark");
}
What I'm missing?

You would generally use $(this).find('bx').removeClass("bx-bookmark").addClass("bxs-bookmark"); to find the child within the link clicked
Here's a way you could do it without the onclick attribute in the html
and I even made it a toggle :-)
<a class='pe-1'><i class='bx bx-bookmark'></i></a>
$(document).ready(function() {
// on any .pe-1 click
$('.pe-1').click(function(){
// find the child with the class .bx
target = $(this).find('.bx');
// if it has class bx-bookmark
if (target.hasClass('bx-bookmark')){
// remove it and add bxs-bookmark
target
.removeClass("bx-bookmark")
.addClass("bxs-bookmark");
}else{
// we assume it has bxs-bookmark already
// so swap it back
target
.removeClass("bxs-bookmark")
.addClass("bx-bookmark");
};
});
});
I wasn't sure what id was for so I removed it. If that's important just let me know what it's for and I'll figure out a solution.
Hope this helps!

Related

Making a dropdown menu for mobile

I'm trying to use media queries and javascript to make a dropdown menu for my page. I have the content i want to be in the menu in a <div> marked with a class, in this case. class="other-pages". My media query has 2 classes in it: .other-pages.closed and .other-pages.open. My goal is to use javascript to change the class once the media query is active to the closed class. Then make a button i have, change the class to the open version.
So here's what I have so far.
let menuContentBase = document.getElementsByClassName('.other-pages');
let mediaQueryMax = window.matchMedia('(max-width: 1080px)');
if (mediaQueryMax.matches) {
menuContentBase.classlist.remove('.other-pages');
menuContentBase.classlist.add('other-pages.closed');
}
When I load this into my browser and look in the debugger however it says menuContentBase.classlist is undefined.
Not entirely sure what to do from here.
Thank you for any advice/recommendations you may have.
Its a simple toggle
let element = document.querySelector(".mq-value")
element.addEventListener('click', (e)=>{
e.target.classList.contains('open') ?
e.target.classList.remove('open') :
e.target.classList.add('open')
})
.open{
color:red
}
<div class="mq-value open"> toggle </div>
I think the issue is in the class name. When it comes to document.getElementsByClassName, you don't need to put . before the class name. Replae this
let menuContentBase = document.getElementsByClassName('.other-pages');
with this
let menuContentBase = document.getElementsByClassName('other-pages');
If you want further information about this, you can refer https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
Also, same for classList not classlist and the L must be uppercase.
if (mediaQueryMax.matches) {
menuContentBase.classList.remove('other-pages');
menuContentBase.classList.add('other-pages.closed');
}
Try this one and let me know if it's works or not. Thank you!

passing values to a function does not work when inside for loop

I'm mapping currencies from a json file and i render the mapped currencies to a component. I have a .php file like this
<div class="currency-switch-container" id="currency_container">
<span style="font-size:12px;font-weight:bold">All currencies</span>
<div id="currency-map" style="margin-top:15px"></div>
</div>
I refer the div in the above component in my js file as follows
let currencyMap = jQuery("#currency-map");
And when my jQuery document is ready i'm doing the following
jQuery(document).ready(function($) {
$.getJSON('wp-content/themes/mundana/currency/currency.json', function(data) {
for(let c in data){
currencyMap.append(`<span onclick="onCurrencyClick(${data[c].abbreviation})"
class="currency-item">
<span>
${data[c].symbol}
</span>
<span>
${data[c].currency}
</span>
</span>`)
}
});
}
and my function is like this
function onCurrencyClick(val){
console.log("val",val);
setCookie("booking_currency", val, 14);
}
Here the function does not work. But if i do not pass anything to the function it seems to work as i can see the log in the terminal.
Hi your expression ${data[c].abbreviation} will put the value into function string without string quotes i.e. the resultant would be onCurrencyClick(abbreviation) while it should be onCurrencyClick('abbreviation').
please use onclick="onCurrencyClick('${data[c].abbreviation}')" instead.
Instead of using the inline onclick, use event delegation. This means that you have a single event listener that handles all the events from the children and grandchildren. The modification is a very minor one seeing the example here below.
A reason for doing this is that you keep your JavaScript inside your JS file. Like now, you encounter a JS error and have to look for it in your HTML. That can get very confusing. Also however inline onclick listeners are valid, they are outdated and should be avoided unless there is absolutely no other way. Compare it with using !important in CSS, same goes for that.
function onCurrencyClick(event){
var val = $(this).val();
setCookie("booking_currency", val, 14);
}
currencyMap.on('click', '.currency-item', onCurrencyClick);
This example takes the val that you try to insert from the value attribute from the clicked .current-item. <span> elements don't have such an attribute, but a <button> does and is a much more suitable element for it expects to be interacted with. It is generally a good practice to use clickable elements for purposes such as clicking.
In the example below you see the button being used and the abbreviation value being output in the value attribute of the <button> element and can be read from the onCurrencyClick function.
jQuery(document).ready(function($) {
$.getJSON('wp-content/themes/mundana/currency/currency.json', function(data) {
for(let c in data){
currencyMap.append(`
<button value="${data[c].abbreviation}" class="currency-item">
<span>
${data[c].symbol}
</span>
<span>
${data[c].currency}
</span>
</button>
`)
}
});
onclick will not work for a dynamically added div tag
Yo should follow jQuery on event
Refer: jQuery on
Stackoverflow Refer: Dynamic HTML Elements

Hashtag in URL for show div base on compare ID

Ok, I will try explain my question.
I need to add class ".active" into already existing class ".jobs", when URL have hashtag same as ID, inside tag with class ".jobs".
Here is working code just for one compare:
$(document).ready(function() {
var hashVal = window.location.hash.split("#")[1];
if(hashVal == 'programmer') {
$("#programmer").addClass('active');
}
});
In practice:
Someone will come to website www.domain.tld/jobs#programmer then I need compare "#programmer" from ULR with all existing IDs in all <div> tags, which also have class ".jobs", and if there will be someone with class="jobs" and also id="programmer", I need to add into this <div> tag class "active".
Is there a way to make jQuery code more variable? Like without having add comparison for each ID name? and also I need to move browser windows on position, where div with that ID it is.
var hashVal = window.location.hash.split("#")[1];
if($('#'+hashVal).hasClass('jobs')) $('#'+hashVal).addClass('active');

How to submit a form by clicking a link javascript

currently I'm trying to make it so that when the user clicks a link it submits the corresponding form via javascript. I used document.getElementById("id").submit() as a basis on how to send the form so my code should act similar to it in my understanding.
Here's the code:
function run(clickedLink){
clickedLink.id.submit(); //I did it like this since document.getElementById just gets the form id and since link and form have similar id's I thought it would send
}
<form id = 'formId'>
<a href = '#' id = 'formId' onclick = run(this)>Link</a>
</form>
I tried going with name = 'formId' too but it still doesn't run as I wanted it too.
Note: doing this since this code iterates dynamically and the id gets updated i.e. formID1, formID2...
Better ways to implement this are welcome too
Modify your function as follows
function run(clickedLink){
clickedLink.parentNode.submit(); // parentNode refers to the form element
}
You cannot use same id on the same page for more than one element. This is against HTML and DOM specifications https://softwareengineering.stackexchange.com/questions/127178/two-html-elements-with-same-id-attribute-how-bad-is-it-really .
You can change it to class if you want to reuse or you can change the id itself of other element. Also links are not recommended to submit the form. Their job is to navigate
Try this:
<a href="#" onclick="document.forms[0].v.value='Link1';
document.forms[0].submit();">Link 1</a>
One Basic thing:
-ID's are used to Uniquely Describe The Element in DOM Hierarchy. Please Don't Repeat it. (it is really bad)
Now to the answer:
function run(x){
var y=findParentForm(x); /* if Id's aren't Unique */
// If iD's are Unique :- var y=document.getElementById("formId");
y.submit();
}
function findParentForm(elem){
/*
This function will find exact parent form
even if link or elem is inside <div> or other complex DOM structure
This will Only return the parent <form> of that elemnt
*/
var parent = elem.parentNode;
if(parent && parent.tagName != 'FORM'){
parent = findParentForm(parent);
}
return parent;
}
<form id='formId' action="Server Side Script" method="GET/POST">
Link <!-- change id of link -->
</form>

How to get link inside div and click it using js

I am trying to write a function for an extension that can find a link inside a specific div and click it. The link has no id or class name, so I was looking for something similar to a CSS selector but with JS without using '$' or 'jQuery' since that will require me to embed a jquery library with the extension.
The div has a class name and then a link inside, so this is the code I have so far --
function COut() {
var a = document.getElementsByClassName('bottom_row').getElementsByTagName('a');
for (var i = 0; i < a.length; i++) {
var elem = a[i],
elem.click();
}
}
This the markup for the div and link -
<div class="bottom_row">
<a onclick="miniAddToCart.closeMiniAddToCart({cmConversionEvent: 'Checkout'})" href="http://www.domain.com/shoppingcart/default.cfm?checkout=1&"><img src="http://www.domain.com/images/eb/minicart/checkout.gif" alt="Checkout"></a>
</div>
Any ideas what Im doing wrong?
getElementsByClassName('bottom_row').getElementsByTagName('a');
getElementsByClassName returns a set, not a single item
getElementsByClassName('bottom_row')[0].getElementsByTagName('a');
^^^
If there can be more than one item with the className, than you will need to loop. And if you support modern day browsers, you can look into querySelectorAll
And finally clicking on a link is not as easy as calling click()
How can I simulate a click to an anchor tag?
If you want it to do to the url, you might be better off just setting window.location.href
If there is a single A tag, I won't prefer to make loop for that. Instead you can just do it like:
function COut() {
var a = document.getElementsByClassName('bottom_row')[0].getElementsByTagName('a')[0];
if(a){
a.click();
}
}

Categories

Resources