Using jQuery to load icon based on <label> contents - javascript

I have a website where the content is dynamically loaded from a database. The contents varies for each label.
One may be generated as General:, whilst another may be generated as TV:.
My question is, is there any way that jQuery could (based on the HTML output for the label) replace the NAME: with a font awesome icon?
So for example:
<label>TV:</label>
Would become:
<i class="fa fa-film fa-2x"></i>

Try
var icons = {
'tv:': 'film',
'edit:': 'edit'
};
$('label').replaceWith(function () {
var text = $(this).text().trim().toLowerCase(),
icon = icons[text];
return icon ? '<i class="fa fa-' + icon + ' fa-2x"></i>' : undefined;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css">
<label>TV:</label>
<label>TsV:</label>
<label>EDIT:</label>

You could use the :contains selector http://api.jquery.com/contains-selector/
$("label:contains('TV')").html('<i class="fa fa-film fa-2x"></i>');

$("label:contains('TV')").html('<i class="YOUR CLASS"></i>');
or if you could add class or id in that label you could change it easily like
$("#ID").html('<i class="YOUR CLASS"></i>');
$(".CLASS").html('<i class="YOUR CLASS"></i>');

You can replace them with JQuery for example
var icons = {
"TV:" : "film"
};
var $labels = $('label');
$labels.each(function(index){
var icon = icons[$(this).text()];
$(this).replaceWith($("<i>").addClass('fa').addClass('fa-' + icon).addClass('fa-2x'));
});
And see Fiddle: http://jsfiddle.net/m19hjnoa/

You could take different aproaches on that.
My personal favorite would be to just send the right label from the server.
otherwise you could run this jQuery Script: http://jsfiddle.net/ehdgL6so/
// try to select as less elements as possible for speed
// for example if they are in a div with class foo try jQuery('div.foo label') instead
var labels = jQuery('label');
// loop throu all labels
labels.each(function() {
// get single label element
var label = jQuery(this);
// get the content (for example "TV:"
var labelContent = label.text();
// replace if the label matches
switch(labelContent) {
case 'TV:':
// if the label contains "TV:" replace the <label> with the <i> element
label.replaceWith('<i class="fa fa-film fa-2x"></i>');
break;
case 'Foo':
// if the label contains "Foo" replace foo with the <i> element
label.html('<i class="fa fa-film fa-2x"></i>');
break;
}
});
Edit:
Or as #cforcloud suggests a short Form like
// note: .html does just replace the string "TV:" but leaves the label element in the DOM, while replaceWith is the way to replace an element
// http://api.jquery.com/replacewith/
jQuery("label:contains('TV:')").replaceWith('<i class="fa fa-film fa-2x"></i>');

Related

changing innerHTML of child element using javascript

I would like to change my icon from expand_more to expand_less in following code
<li class="dropdown-bt" onclick="dropdown('content');">
<a>dropdown-content <i class="material-icons">expand_more</i></a>
</li>
I am going to use same code multiple times so it would be better to using function multiple times. I thought of using ID for every piece of code but it would be to hectic. So I want to write single function do it but I don't know how, so please help.
Just pass an object event as a parameter, say e to your dropdown() and use the textContent property to retrieve the current element content, check it's value and replace the content with another text content like this:
var btn = document.getElementById("dropdownBt");
function dropdown(e) {
var innerText = e.target.children[0];
if(innerText.textContent == "expand_more") {
innerText.textContent = "expand_less";
} else {
innerText.textContent = "expand_more";
}
}
btn.addEventListener('click', dropdown);
<li class="dropdown-bt" id="dropdownBt"><a>dropdown-content <i class="material-icons">expand_more</i></a></li>

Summernote - Insert Text and keep formatting style

I am currently trying to insert a string of text from a dropdown list into the Summernote text editor. However, upon insertion, the string closes any formatting tags, such as <'strong'>, <'p'>, and more.
Here is an example of the HTML after I have inserted the string "AND"
Bob AND I Loves Ice Cream and Cake. How about You?
<p><span style="font-size: 12px;"><b>Bob </b></span>AND <span style="font-size: 12px;">
<b>I </b></span><span style="font-size: 12px;">
<b>Loves Ice Cream and Cake. How about You?</b></span>
I need to be able to prevent the auto-closing and auto-opening of tags to the right and to the left of where the cursor was. I was looking into using the insertNode() and insertText() functions, but both of these end up doing the same thing.
Any ideas? Thanks!
EDIT: Here's a sample of the code that inserts at the cursor. I am currently extending Summernote's button with the UppercaseButton.
var UppercaseButton = function (context) {
var ui = $.summernote.ui;
// create button
var button = ui.button({
contents: '<i class="fa fa-child"/> Uppercase',
tooltip: 'Highlight a data attribute that you would like to make uppercase',
click: function () {
var range = $('#taBody').summernote('createRange');
var newText = range.toString();
console.log("newText: " + newText);
console.log(range);
context.invoke("editor.insertText", newText.toUpperCase());
}
});
return button.render(); // return button as jquery object
}
Here's my approach. This should grab the current node context the cursor is in and then append the desired text into that node
function insertAtCaret(text) {
// deleteContents() will replace any text that is currently highlighted, if any
let newRange = $("#taBody").summernote("getLastRange").deleteContents();
// Insert the desired text inside the formatted tag of the first part of the highlighted text. That way the formatting applies to the inserted text
newRange.sc.textContent = newRange.sc.textContent.substring(0, newRange.so) + text + newRange.sc.textContent.substring(newRange.so, newRange.sc.textContent.length);
// Update the cursor position to just after the inserted text
$("#taBody").summernote('setLastRange', $.summernote.range.create(/* start container */newRange.sc, /* start offset */ newRange.so + text.length).select());
}
var UppercaseButton = function (context) {
var ui = $.summernote.ui;
// create button
var button = ui.button({
contents: '<i class="fa fa-child"/> Uppercase',
tooltip: 'Highlight a data attribute that you would like to make uppercase',
click: function () {
insertAtCaret(newText.toUpperCase())
}
});
return button.render(); // return button as jquery object
}

Data attribute is returning undefined

I am using jQuery to set a data attribute filtername on an onClick which works fine.
$('#tag-group ul').append('<li><i class="fa fa-times" aria-hidden="true" data-filtergroup="'+filterGroup+'" data-filtername="'+filterName+'"></i>'+text+'</li>');
It renders out on the screen ok as
<li><i class="fa fa-times" aria-hidden="true" data-filtergroup="location" data-filtername="Melbourne"></i> Melbourne</li>
I am then trying to pick it up again on another onClick but it comes back as undefined. When I console log $(this).text(); it works but when I console log $(this).data('filtername'); it is undefined. Is the dom hiding it if it is generated by jQuery?
$(document).on('click','#sau-filter-tags ul li', function(event){
var text = $(this).text();
var filterName = $(this).data('filtername');
console.log(filterName); //Undefined
});
filtername is attribute of i tag in li.
You need to select i tag :
$(document).on('click', '#sau-filter-tags ul li i', function(event) {
var text = $(this).text();
var filterName = $(this).data('filtername');
console.log(filterName); //Undefined
});
or you need to attach event to li and find I in this , Example:
$(this).find('i').data('filtername')
You are targeting a data attribute on i tag. So you have to create an event upon i
$(document).on('click','#sau-filter-tags ul li i', function(event){
var text = $(this).text();
var filterName = $(this).data('filtername');
console.log(filterName); //Undefined
});
You are accessing the attribute on your containing <li> rather than the <i> inside. Try the following:
$('#sau-filter-tags li').on('click', function () {
var i = $(this.firstElementChild)
var text = i.text()
var filterName = i.data('filtername')
console.log(filterName) //=> 'Melbourne'
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li><i class="fa fa-times" aria-hidden="true" data-filtergroup="location" data-filtername="Melbourne"></i> Melbourne</li>

How do I change the last textual node child in JavaScript

My Solution (EDIT : 2015-12-08) :
// FIRST WE GET THE PARENT ELEMENT
var parentEstim = document.getElementById("onglet_estim");
// MAKE A TABLE OF HIS CHILD
var enfantsEstim = parentEstim.childNodes;
// KNOW HOW MANY CHILDREN THE PARENT ELEMENT HAVE WITH .length
var Nbenfants = enfantsEstim.length;
....
for (var i = 0; i <= Nbenfants; i++) {
// IF THE CHILD ELEMENT [i] IS A HTML ELEMENT
if (enfantsEstim[i].nodeType === 1) {
enfantsEstim[i].lastChild.data = ''; // REMOVE LAST TEXT NODE
enfantsEstim[i].classList.remove('isActive');
}
document.getElementById('onglet_estim').style.width = '220px';
ClickedElement.className = 'isActive';
// ADD NEW VALUE IN THE LAST TEXT NODE FOR THE CLICKED ELEMENT
ClickedElement.lastChild.data = ' Gares';
}
DEMO : http://codepen.io/Zedash/details/pjMEMY
The Problem :
I have a little problem, I want to change the last textual node child value of a link <a> element.
For exemple, for the first link, we see the word "Saisie" wrote in it and I want to remove the text in this element if the user click on an other link and add a right text for the clicked element.
function changeInputAdresse(ClassName) {
if (ClassName.className !== 'isActive') {
ClassName.className = 'isActive';
switch(ClassName.id) {
case 'linkGares' :
ClassName.insertAdjacentHTML('beforeEnd',' Gares');
ClassName.previousElementSibling.classList.remove('isActive');
ClassName.nextElementSibling.classList.remove('isActive');
ClassName.previousElementSibling.insertAdjacentHTML('beforeEnd','');
ClassName.nextElementSibling.insertAdjacentHTML('beforeEnd','');
break;
}
}
};
// THE CODE IS NOT FINISHED OF COURSE !
a {
text-decoration:none;
color:#000;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>
<a id="linkSaisie" class="isActive" href="#n" onclick="changeInputAdresse(this);"><i class="fa fa-map-marker"></i> Adresse</a>
<a id="linkGares" href="#n" onclick="changeInputAdresse(this);"><i class="fa fa-train"></i></a>
<a id="linkAeroports" href="#n" onclick="changeInputAdresse(this);"><i class="fa fa-plane"></i></a>
<a id="linkLoisirs" href="#n" onclick="changeInputAdresse(this);"><i class="fa fa-fort-awesome"></i></a>
<!--THE PART OF CODE WHERE I HAVE SOME PROBLEMS-->
Thanks for your ansewers ! :)
I don't quite get what you exactly would like, but to target and change the element after an italic I would use this jQuery and vanilla JS combination:
$("#myLink").find(">i").get(0).nextSibling.nodeValue = "Changed text";
DEMO: http://jsfiddle.net/u9jq2bvy/
IIRC there is no jQuery method to target a text node, so you need some native JS.
Please let me know if I misunderstood the question and I'm gonna delete my answer.
UPDATE
Based on the comment here is a possible solution.
$(document).on("click", ".myLink", function() {
// clear all texts
$(this).parent().find("a>span").text("");
$(this).addClass("active");
$(this).children("span").text("Active text");
});
DEMO http://jsfiddle.net/u9jq2bvy/1
And here is a modified version which simply shows/hides the spans.
DEMO http://jsfiddle.net/u9jq2bvy/3/
You can use jQuery siblings
changeInputAdresse(element){
element = $(element)
if(!element.hasClass('isActive')){
element.addClass('isActive');
element.siblings().removeClass('isActive');
element.text(element.attr('id').replace('link','')) //if that's the way you get value
element.siblings().text('')
}
}

I want to open link Using jquery

I want to open link using Jquery by clicking on anchor by using its anchor id in change function. Please help me to open it
<div id="div1" style="display:none">
<a id="0" href="http://www.friferie.dk/inspiration/Belgien">Belgium</a>
<a id="1" href="http://www.friferie.dk/inspiration/Bulgarien">Bulgarien</a>
<a id="2" href="http://www.friferie.dk/inspiration/Danmark">Danmark</a>
</div>
**I want to pass id then open particular href into it**
$ ("").change(function () {
}
Long version (for readability):
$ ("#someselector").change(function () {
// Get selected value
var val = $(this).val();
// Use the selected value to create a jQuery ID selector to get the link
var link = $('#' + val);
// get the href value
var href = link.attr("href");
// Change the browser location
window.location = link;
});
Or simulate a link click:
$ ("#someselector").change(function () {
// Get selected value
var val = $(this).val();
// Use the selected value to create a jQuery ID selector and get the link
var link = $('#' + val);
// Click the link
link[0].click();
});
I tend to use [0].click() and not the jQuery click() here as it hits the underlying browser implementation (and we won't care about the jQuery extras as the page will change).
Notes:
Both examples can be shortened, e.g. by removing local variable, but this was for explanatory purposes
e.g.
$ ("#someselector").change(function () {
window.location = $('#' + $(this).val()).attr("href");
});
or
$ ("#someselector").change(function () {
$('#' + $(this).val())[0].click(); // Or `).click()` is you want it shorter
});
yes with select by a dropdown of a dropdownlist using its id
As per this comment, you can do this :
$("#dropdown").change(function(e){ // change event on dropdown
$('#'+this.value).click(); // and apply the click on specific anchor
// $('#'+this.value).get(0).click(); // comparing to selected value
});
<div id="div1" style="display:none">
<a id="0" href="#" onclick="onChange(this)">Belgium</a>
<a id="1" href="#" onclick="onChange(this)">Bulgarien</a>
<a id="2" href="#" onclick="onChange(this)">Danmark</a>
</div>
<script>
function onChange(obj){
var id= $(obj).attr("id");
switch(id){
case "0":
window.location.href="http://www.friferie.dk/inspiration/Belgien";
break;
case "1":
window.location.href="http://www.friferie.dk/inspiration/Bulgarien";
break;
case "2":
window.location.href="http://www.friferie.dk/inspiration/Danmark";
break;
}
}
</script>

Categories