Insert variable into file path string in javascript - javascript

Depending on the user selection the variable "team" contains different team names as string. I want then display the according team logos which are saved as .png files. Therefor I want to insert the variable's string into the file path. How to do that?
Thank you.
JS:
$('ul.subbar li a').on('click', function(e) { // User clicks on a team in the navbar
e.preventDefault(); // Stop loading new link
var team = $(this).html(); //assign clicked team name to variable
console.log(team);
$('.selectedClub').html(team);
$('.teamLogo').src("'images/Clubs/Germany/' + 'team' + '.png'").alt(team);
});
html:
<div class="topRow">
<div class="team">
<div class="teamLogo">
<img class="teamLogo" src="images/man united.png" alt="Manchester United">
</div>
<div class="selectedClub">Manchester United</div>
</div>
</div>

You have a problem here:
$('.teamLogo').src("'images/Clubs/Germany/' + 'team' + '.png'").alt(team);
Should probably be something like:
$('.teamLogo').attr('src', 'images/Clubs/Germany/' + team + '.png').alt(team);
(without the extra quotes)

Better answer is to use string interpolation
$('.teamLogo').src(`images/Clubs/Germany/${team}.png`).alt(team);

Related

Using other attribute instead of id in html and javascript

I am making a project of a chat app, I made a code that if the user is not your user it will be in the left side, and if the user is your user it will be on the right side, the code I do works, but there is a single error. The problem is that I do this:
html
<div class="msg right-msg" id="side">
<div class="msg-img" style="background-image: url(https://image.flaticon.com/icons/svg/145/145867.svg)"></div>
<div class="msg-bubble">
<div class="msg-info">
<div class="msg-info-name">{{ chat.user }}</div>
<div class="msg-info-time"></div>
</div>
<div class="msg-text">{{ chat.message }}</div>
</div>
</div>
javascript
$( "#side" ).each(function() {
//console.log( index + ": " + $( this ));
var users = $(".msg-info-name").text()
if (users != me) {
$("#side").removeClass("msg right-msg");
$("#side").addClass("msg left-msg");
};
});
The problem is that there are many of the same html code(That has the same id, class, etc..), So I realized that I can use id in only one, I use id and this was the product Image of the product, it only change the place in the first one, So that doesn´t work.
So I try using class but instead of changing the first one side it change nothing, so class doesn´t works. What can I do?, is another way to loop into all of this, ALSO, the javascript example is using id's. thank for the help
use class not id for multiple elements.
$( ".msg" ).each(function() {
var users = $(this).find(".msg-info-name").text();
if (users != me) {
$(this).removeClass("msg right-msg");
$(this).addClass("msg left-msg");
};
});

paragraph tags in tweet field from web page

I put together a quote machine as an exercise of freecodecamp.com. You click the button, you get a quote. Then, if you want, you can tweet the quote by clicking the "Tweet It" button. I had a lot of trouble figuring out how to get the quote to populate the tweet field. I finally just looked at someone else's code on the issue, and now it is populating.
The problem: it is populating <p> and </p> tags with every quote. Example:
"<p>When typography is on point, words become images.</p>
" Shawn Lukas
It's also annoying that the second set of quotation marks always appears on the line below next to the author's name.
I'm not sure how the tags are getting in there, but I'd like help clearing them out. Here's my code:
HTML
<div id="container">
<div class="content">
<div id="quote" class="triangle-isosceles">
<p>
<span class="msg"></span>
</p>
</div>
<p id="author"><span class="nme"></span></p>
</div>
<button type="button">Get Quote</button>
<a class="twitter-share-button" id="tweet-quote" target="_blank">
<button type="button" class="btn btn-primary">Tweet it!</button>
</a>
</div>
JS
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
<script>
$.ajaxSetup({
cache: false
});
$('button').on('click', function() {
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
var quote = a[0].content;
var author = a[0].title;
$(".msg").empty().append(quote + "<p>— " + author + "</p>")
$('#tweet-quote').attr('href', 'https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=' + encodeURIComponent('"' + quote + '" ' + author));
});
});
</script>
I'm omitting the CSS. I can't get a jsfiddle to work (never can), but here's the CodePen link: https://codepen.io/dtarvin/pen/pePowj
Update: just found a quote with an apostrophe and got back those numbers instead of the symbol. Not sure how to handle that when the quotes are random.
Thanks!
you have "<p>— " + author + "</p>" in the append code, regarding the html entity code you need to parse the quote to switch them to the normal version. Also you might need to remove tags within the a[0].content variable. if you have no control over what is returned, you may need to do a lot more filtering to catch stuff like this.
Or if you have access to the serverside script, then use this to get the quote and return the cleansed quote.
For instance, if you visit the url https://quotesondesign.com/wp-json/posts you will see the <p> tags within the quote themselves.
So you basically need to clean the content of the content variable.
for instance to remvoe the p tag within the content string try:
var quote = a[0].content.replace(/<p[^>]*>/g, '').replace(/<\/p>/g, '');
If you need these tags in to display then you could add a seperate function that on pressing the tweet it button, will do this for you.
So you have them on the browser but on tweeting its all striped and good on twitter
Try this it work
<script>
$.ajaxSetup({
cache: false
});
$('button').on('click', function() {
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
var quote = a[0].content;
var author = a[0].title;
$(".msg").empty().append(quote + author);
var html = quote + author;
var div = document.createElement("div");
div.innerHTML = html;
var text = div.textContent || div.innerText || "";
$('#tweet-quote').attr('href', 'https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=' + encodeURIComponent( text ));
});
});
</script>

Retrieve name value from button in javascript

I have the following HTML:
<div class="dropdown" data-offers-filter-segments="">
<button class="toggle--dropdown" name="toggle-segment-cagetories-list">
<span class="dropdown__label" id="dropdown__labelAllCategories">All Categories</span>
</button>
<div class="dropdown__content" hidden="hidden">
Which renders a dropdown, when clicked a new class is appended which is called is-dropped so the parent div will look like this once its been clicked on class="dropdown is-dropped"
Now using Javascript I'm trying to retrieve name="toggle-segment-cagetories-list" which we will use within DTM (Adobe Tag Manager) as an eVar value but I'm uncertain how I go about retrieving that name value, so far I have the following javascript:
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
if(hasClass(document.getElementsByClassName('dropdown')[0], 'is-dropped')){
// Now get the name value ?
}
else {
alert("false");
}
Now I'm pretty new to javascript so if someone can shed some light in how I go about getting the name value and passing it to DTM I would highly appreciate it.
use document.querySelector:
<div class="dropdown is-dropped" data-offers-filter-segments="">
<button class="toggle--dropdown" name="toggle-segment-cagetories-list">
<span class="dropdown__label" id="dropdown__labelAllCategories">All Categories</span>
</button>
<div class="dropdown__content" hidden="hidden">
<script>
var button=document.querySelector('div.is-dropped button.toggle--dropdown');
var name=button&&button.name||'';
alert(name);
</script>
if you want to use your own data-attributes, you need start your attribute name with 'data':
<button class="toggle--dropdown" data-name="toggle-segment-cagetories-list">
In order to retrieve the value of the attribute, you can do as shown in the example below:
var article = document.getElementsByClassName('toggle--dropdown');
article[0].dataset.name // article[0] because getting elements by className returns an array

strange variable scope in jQuery

I know scope in javascript in sometimes tough but this time I suspect the issue may be jQuery execution order. In the following code I try to define a simple HTML element (simulates a button) in javascript and pass different text to it when mounting it in HTML using jQuery:
var name;
var buttonsecondary = '<div class="buttonsecondary clicked"><p>'+name+'</p></div>';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="content-item" id="things4">
<a href="aFabrica.html">
<div class="itemHome">
<div class="bg" id="buttonsecondaryfabrica"></div>
<script>
$(document).ready(function() {
var name = "A Fábrica";
$("#buttonsecondaryfabrica").after(buttonsecondary)
})
</script>
</div>
</a>
</div>
<div class="content-item">
<a href="lojas.html">
<div class="itemHome">
<div class="bg" id="buttonsecondaryloja"></div>
<script>
$(document).ready(function() {
var name = "Loja";
$("#buttonsecondaryloja").after(buttonsecondary)
})
</script>
</div>
</a>
</div>
The problem is that I get the same text on both buttons: "Store" although in the first alert getting "Street" and in the second "Store"...
Does anyone know how to explain it?
The problem is that the buttonsecondary variable already contains the final HTML of the button because it's merely a concatenated string.
You need to generate the desired HTML each time:
function generateButton(name)
{
return '<div class="buttonsecondary clicked"><p>' + name + '</p></div>';
}
Then:
var name = "A Fábrica";
$("#buttonsecondaryfabrica").after(generateButton(name));
And
var name = "Loja";
$("#buttonsecondaryloja").after(generateButton(name));
In your original code, you are creating a string with variables that are changed later on. When you change the variables, the string does not get updated because the variables are not bound. You need to create a new string if you want to pass in a new value for the name.
Change this:
var buttonsecondary = '<div class="buttonsecondary clicked"><p>'+name+'</p></div>';
To this:
function createSecondaryButton(name) {
return '<div class="buttonsecondary clicked"><p>' + name + '</p></div>';
}
Or, since you are using jQuery:
function createSecondaryButton(name) {
return $('<div>').addClass('buttonsecondary clicked')
.append($('<p>').text(name));
}
Then simply call the function:
$("#buttonsecondaryfabrica").after(createSecondaryButton('A Fábrica'));
$("#buttonsecondaryloja").after(createSecondaryButton('Loja'));

Open the popup of the particular div

When I click on the class="team-single" of id="team-1" then it should open the .team-popup of that particular id.
But it doesn't seem to work.
<div class="team-single" id="team-1">
<div class="team-popup">
<span class="close-btn">x close</span>
</div>
</div>
<div class="team-single" id=team-2>
<div class="team-popup">
<span class="close-btn">x close</span>
</div>
</div>
This is what I am using for js
jQuery(".team-single").click(function(e) {
var currentID = this.id || "No ID!";
jQuery(" #currentID .team-popup").css({
display :"block",
});
});
I'd reduce what you have to just:
jQuery(".team-single").click(function(e) {
jQuery(this).find('div.team-popup').show();
});
Use find() with this to get current context
jQuery(".team-single").click(function(e){
jQuery(this).find(".team-popup").css({ display :"block",
});
//Or
// jQuery(".team-popup",this).css({ display :"block",
});
});
Why your code did not work :
You stored the ID in a variable, and to access this variable in a selector use:
jQuery("#"+currentID+" .team-popup").
Variables aren't substituted inside strings. If you want to use a variable in a string, you have to use concatenation:
$("#" + currentID + " .team-popup")
But the answers using $(this).find() are better solutions. I'm just posting this so you can understand what was wrong with your code.
Use this:
jQuery(".team-single").click(function(e){
$(this).children().css("display", "block");
});

Categories

Resources