I have a requirement to use tags on a web page. No problem--Materializecss handles that. However, my tags can be any of several types, so each tag can be of a different color to indicate the type. Again, no problem.
Unfortunately, to support Materializecss keyboard functions, I need to rework it. Before, I was using a hack to just add the divs myself and giving them a class "chip". Now I'm using the materialize addChip function, which is only illustrated to have 'tag' and 'data'.
How do I add the color and textcolor classes to those chips? It seems like a simple thing. The javascript that creates the tag is:
instance.addChip({ tag: 'tag text', });
I'd like to know if there's something like:
instance.addChip({ tag: 'tag text', color: 'teal', text-color: 'white-text', });
Anyone know?
So, my example was that I'm adding a tag from a form--so there's easier ways to do this. However, this is how to add the chip, adjust the styling, and add custom attributes so that you have better control of the way the tag is displayed. You can use this pattern to keep track of pictures and custom fields for database primary keys and stuff.
//get the instance
var chipInstance = M.Chips.getInstance($('.chips'));
//add the chip. id is generated elsewhere and is the primary key for database
chipInstance.addChip({
tag: 'text',
textColor: 'white-text',
tagColor: 'red',
tagId: id,
});
//get the data
var dataArray = chipInstance.chipsData;
//last added data
var myData = dataArray[dataArray.length - 1];
//last added chip div
var allChips = $(chipInstance.$chips);
//get the last chip (the one we just added)
var myChip = allChips.last()[0]; //the data is in the 0th position
$(myChip).addClass(myData["tagColor"]); //add the 'red' class
$(myChip).addClass(myData["textColor"]); //add the 'white-text' class
//need to preserve this because it will be the database key to handle any deletes.
$(myChip).attr('data-id', myData["tagId"]);
$(myChip).attr('title', 'more title text'); //adjust attributes
Related
I'm testing out some jQuery and want to update a image when hovering over a specific div or link block.
So what i was trying to do is when hovering over .test-block get the hidden text with the url and update it on .large-image-2. It can't seem to get the specific text on hover.
This is the code i have come up with:
$('.test-block').on('onmouseenter', function() {
let myUrl = $(this).find('.display-hidden').text();
$('.url').text(myUrl);
});
Im testing on this page: https://jquery-testing.webflow.io/update-image the three bottom div's and bottom picture on right is what i want to use.
Thanks in advance!
There are a few issues with your example. Mainly the way you register the event handler.
For jQuery the correct way would be $(target).on('mouseenter') - Ommit the on... part for the event you want to register when doing it through jQuery.
I would probably implement the functionality you're looking for in a less specific way and with simpler handles like the following:
$(function () {
let divs = $('[data-image-target][data-image-url]');
divs.on('mouseenter', function () {
let that = $(this)
const target = that.data('image-target')
const url = that.data('image-url')
$(target).attr('src', url);
})
divs.first().trigger('mouseenter')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div
data-image-target="#my-target-image"
data-image-url="https://dummyimage.com/600x400/000/fff&text=one">
Hover One
</div>
<div
data-image-target="#my-target-image"
data-image-url="https://dummyimage.com/600x400/000/fff&text=two">
Hover Two
</div>
<div
data-image-target="#my-target-image"
data-image-url="https://dummyimage.com/600x400/000/fff&text=three">
Hover Three
</div>
<img id="my-target-image">
Explanation:
Data attributes:
Two data attributes are getting used in my example: data-image-target and data-image-url.
Using data attributes on the elements you want the event to be fired on will make your script a bit more robust and less prone to errors, since the event registration is bound to the two attributes being present using attribute selectors for the jQuery selector $([data-image-target][data-image-url]) instead of arbitrary classnames and/or ids.
The data-image-target should have a CSS selector that points to the <img> element(s) you wish to switch the src url on, while the data-image-url should hold the url of the image you want to switch to.
The code above could even replace your existing functionality for the top 3 images on your page.
This code worked
$(function () {
let divs = $('[data-image-target][data-image-url]');
divs.on('mouseenter', function () {
let that = $(this);
const target = that.data('image-target');
const url = that.data('image-url');
$(target).attr('src', url);
});
});
Thanks to Morten for providing. With Webflow i also had to do Command + Shift + O to turn off responsiveness to the image. (when on image settings)
Attributes:
Name: data-image-target
Value: #my-target-image
And
Name: data-image-url
Value: (image url, in my case Webflow: https://uploads-ssl.webflow.com/something)
These two attributes to each hover element.
Name: id
Value: my-target-image
This to the image element to show images. (if Webflow; "my-target-image" goes in the ID field in element settings.
I use the rich text editor quill.js in a web project. As I already know I can use the quill.getSelection() method to retrieve the index of the cursor. Like getSelection() I would like to get the index of the cursor without the user having to click, i.e. the index of the cursor when he hovers over the editor text.
I would like to implement the following functionality:
When I hover over a word, the website shows me information about this word. For this I need the current index of the cursor.
How could I do that?
I have found a solution. For this I use my own blot AnalysisBlot, which has a custom attribute analysisid:
let Inline = Quill.import('blots/inline');
class AnalysisBlot extends Inline {
static create(analysisid) {
let node = super.create()
node.setAttribute('analysisid', analysisid);
return node
}
}
AnalysisBlot.blotName = 'analysisitem';
AnalysisBlot.tagName = 'analysisitem';
Quill.register(AnalysisBlot);
Each element created with it has its own ID, which is passed on during the creation. For each element of this blot I have added a hover-event listener:
$("analysisitem").hover(enterHoverOverAnalysisItem, leaveHoverOverAnalysisItem);
In the functions I can then query the ID attribute and display context specific information.
I have one input field that facilitates a person having a conversation but playing both roles in the convo. I want to get as close as I can to what its like to have a text conversation, but I cannot seem to sort out how to style the text when it comes through.
As of the moment, the user types the text and hits one of two buttons, each is loaded with the following function to pull the text, create a div, text node, append them and place in the page.
I tried styling the initial input but that simply makes the input field styled, does not affect the actual output.
I tried adding style at each step of the way, to the variable I saved the input in, to the p, the div, the text node, and after placing it in the doc... each time the function failed.
I tried the attribute method and an innerhtml approach.
What would work? At minimum I would love the function to bold and right align the text. Next best would be to append it with the contents of an ng-app so it says Me: (text here), then My future self: (text here)... which I sense would just involve a string set to a variable.. but setting x = {{name}} caused the function to fail..
I know theres a way to use firebug to understand these failures, but I am not quite understanding that yet. Any suggestions?
<script>
function changeTextComment4(destination){
// to be modified from the above to change the location of the dump
// this function ADDS a comment from the comment field to the div w id comment near it...
var userInput = document.getElementById('userInputS1').value;
// get the input from the user
// 3 make the div a panel
var para = document.createElement("P");
// assignment of attributes
var t = document.createTextNode(userInput);
para.appendChild(t);
// add comment area
// place the item
var destination = document.getElementById(destination)
destination.insertBefore(para, destination.firstChild);
document.getElementById('userInputS1').value = "";
document.getElementById('userInputS1').focus();}
</script>
you can add style by referring to the selector
#userInputS1{
color : #F00;
}
I'm using blogger to create posts and the post layout is as follows:
Post Title
Labels
Content
Author
When creating a post with multiple labels they will show like this for example:
Labels: Alternative, New Music, Imagine Dragons
My question is, how could I go about displaying only the "Genre" in this case "Alternative" so it would display like this:
Labels: Alternative
Blogger doesn't support php so this would have to be done i believe with JavaScript/jQuery where I could filter the text inside the labels div. However I'm not very skilled with that.
UPDATE
MANY THANKS TO Chirag64 FOR THIS!
Anyone using blogger will find this very useful in selecting certain labels to display on your posts.
Final product can be viewed here:
jsfiddle.net/3apZ4/13/
You can use the following JavaScript code to remove the other genres except for the first one.
//Remove genres not matching the listOfGenres list
var labels = document.querySelectorAll(".post-labels a");
var listOfGenres = ["Alternative","Pop"];
for (i=0; i < labels.length; i++) {
if (listOfGenres.indexOf(labels[i].textContent) == -1)
labels[i].remove();
}
//Remove trailing commas.
var postLabels = document.querySelector(".post-labels");
postLabels.innerHTML = postLabels.innerHTML.replace(/\,/g, "");
Working JSFiddle.
You can do it using css and jquery.
1) First separate each labels with seperate div's
2)Create a style for a class in css like
.hidden-class
{
display:none;
}
In jquery,on some condition add the hidden-class to the div.
$( "id" ).addClass( "hidden-class" );
if you want to remove
$( "id" ).removeClass( "hidden-class" );
in javascript
To add
document.getElementById('id').className += 'hidden-class'
To remove
document.getElementById("id").className = document.getElementById("id").className.replace(/\bhidden-class\b/,'');
I "learned" JavaScript a few months ago but quickly picked up Python and spent the past few months writing programs in that language, so I decided it would be a good idea to go back and actually learn JavaScript. Right now I'm making a very simple "blog" with JS that takes the title of the post, generates a hash link from the post, and creates a recent posts section where you can click the link to jump to the post in the page.
For instance, say one of the posts is formatted like this:
<h2 class="post">Another post for you</h2>
<h4>I know you love these</h4>
With multiple posts, and an empty container at the bottom, which will be used to append the recent posts links:
<div id="get-post"></div>
My JS code basically grabs each title with the post class and creates a hash link from the element's title (removing spaces and commas). It then creates and appends a text node consisting of the post title, and then appends the entire link into the get-post container.
var postList = $('#get-post');
var post = $('.post');
function generateRecentPosts() {
post.each(function() {
// Create link from post title that will be used to
// access that post.
var postLink = document.createElement('a');
// Create text node from post title that will be appended
// to the postLink.
var text = document.createTextNode($(this).html());
// Add elements to the DOM.
postLink.href = createLocalLink($(this));
postLink.appendChild(text);
postList.append(postLink);
postList.append('<br />');
});
}
function createLocalLink(elm) {
// Creates the href link that will be used to go to a blog post.
// For example, if the title of the elm parameter is "My Post",
// a link is created called #My-Post that will be used to access
// that post.
elm.id = elm.html().replace(/,/g, '').replace(/\s/g, '-');
console.log(elm.id); // Make sure the ID is added.
return '#' + elm.id;
}
generateRecentPosts();
My problem is that the links it generates to not point to the ID created for each title. When I click on the link, I can see that it successfully created the href hash #My-Post and added it to the anchor tag, but it doesn't take me to the post title.
Example: http://jsfiddle.net/samrap/GQtxL/
I even added a console log function to make sure the ID is being added to the title as I thought that was the problem, but it isn't because the console is printing the correct new ID. I could really use some help in figuring out where exactly the problem is here.
Your h2 tags need to have an id or name attribute that corresponds with the link, that is what makes internal links work. The id is not getting added because you are accessing a jQuery object as if it were a DOM node (elm.id = ...). Modify your createLocalLink function to use jQuery's attr method to set the id property:
elm.attr('id', elm.html().replace(/,/g, '').replace(/\s/g, '-'));
Additionally, since you have jQuery available you could whittle your code down to:
var $this = $(this),
link = createLocalLink($this);
var $postLink = $('a', {
text: $this.text(),
href: link
})
postList.append($postLink).append('<br />');
Here is your fiddle updated: http://jsfiddle.net/GQtxL/1/
This is because your link uses the href = "#My-Post" but none of the posts has the ID "My-Post". It only has a class "post".
This happens because the argument that your are passing to the createLocalLink() function is a DOM Node. But by doing elm.id you are not changing the DOM property but adding another property to the "elm" object. Thus your "elm" object is
x.fn.x.init[1]
0: h2.post
context: h2.post
id: "Another-post-for-you"
length: 1
__proto__: Object[0]
Thus the actual post never gets the attribute ID only "elm" object gets it. Note the empty ID attribute below
draggable: false
firstChild: text
firstElementChild: null
hidden: false
id: ""
innerHTML: "Another post for you"
innerText: "Another post for you"
Thus your document has no element with the ID "My-Post". You can view the source of your HTML to verify this.
For internal links to work there should be an element with the same ID as that used in the href attribute of the link.
For example
<div id="post1">
Your Post Here
</div>
<!--just to show the effect of moving to the post-->
<div style="clear:both; height:900px"></div>
Click Here
This would work because there is an element with the id "post1" and the link uses the href "#post1" which links it to the corresponding element. Hence, add the corresponding id to your post as well (other than your link) for it to work.
In function createLocalLink you are using elm argument as dom node, but actually passing a jQuery wrapped object to it, which don't have id property. To get it work, use elm.get(0).id = ... or elm.attr('id', elm.text().replace(/,/g, '').replace(/\s/g, '-'););