how to use a queryselector on object HTMLInputElement - javascript

I am trying that when the text field has focus, the div is selected with the class:autocomplete, this is an example to understand my idea, in my real problem it is more complex. I simply need that once the element that has the focus is identified, select the nearest div with .autocomplete class on the same level, I want to get it this way. I know that in css I should use something like:
input ~ div.autocomplete
($event.target is input in my case)
but I don't know how to do it in this case. Thank you.
function fn_selectAutocompleteClass($event) {
console.log(($event.target));
}
.selectAutocomplete {
background: green;
}
<input id="text" type="text" onfocus="fn_selectAutocompleteClass(event)">
<i class="icon"></i>
<div class="autocomplete">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rerum itaque placeat, ad vel reprehenderit illo, harum nemo laudantium, dolorem unde aut distinctio! Consectetur vitae deleniti veritatis autem numquam officia eaque.</div>

In this case you can access the .autocomplete using the querySelectorAll on the target elements parent like below snippet. Get the 0th index as that will be the first element matching the selector query.
function fn_selectAutocompleteClass($event) {
console.log($event.target.parentNode.querySelectorAll('.autocomplete')[0]);
}
.selectAutocomplete {
background: green;
}
<input id="text" type="text" onfocus="fn_selectAutocompleteClass(event)">
<i class="icon"></i>
<div class="autocomplete">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rerum itaque placeat, ad vel reprehenderit illo, harum nemo laudantium, dolorem unde aut distinctio! Consectetur vitae deleniti veritatis autem numquam officia eaque.</div>
Hope this helps :)

Related

How to create function that swaps divs with different ids?

I'm trying to create function in js to swap content of webpage using .style.display = "none" or "block" but the main problem is that there are few different divs with different id's for that. The main aim of doing this is chagning content after clicking specific buttons without loading new page. The biggest problem for me is creating script which will change "id"
independently of what id was before. Normally I could write all of id's one by one and just swap them but this is not the case. Content should be changed automatically so no matter what id was before it will replace for specific one after pressing button.
I have tried with querySelector in many ways by changing id with class, by using remove / set Attribute but none of these methods work for me. Im trying to write this fuction for 2 weeks and I don't have any ideas.
I'm worried that bootstrap classes may cause problem with this...
Can someone help me with this? Any tips?
This is my first post here so if I did something wrong, sorry for that.
I cannot paste here my code as everything is on my company laptop which I left when I was finish my job.
Here is an agnostic approach using no HTML ids or classes.
const container = document.querySelector('.container');
const buttons = container.querySelectorAll('button');
const divs = container.querySelectorAll(':scope > div');
function handleButtonClick() {
this.previousElementSibling.classList.toggle('hide');
}
buttons.forEach(button => {
button.addEventListener('click', handleButtonClick);
});
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 20px;
}
.hide {
display: none;
}
<div class="container">
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis sed, dicta quasi in blanditiis nam atque odio, nobis a. Eos incidunt debitis tenetur rerum, esse ratione quisquam possimus quasi nam.</p>
<button>Toggle Content</button>
</div>
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis sed, dicta quasi in blanditiis nam atque odio, nobis a. Eos incidunt debitis tenetur rerum, esse ratione quisquam possimus quasi nam.</p>
<button>Toggle Content</button>
</div>
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis sed, dicta quasi in blanditiis nam atque odio, nobis a. Eos incidunt debitis tenetur rerum, esse ratione quisquam possimus quasi nam.</p>
<button>Toggle Content</button>
</div>
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis sed, dicta quasi in blanditiis nam atque odio, nobis a. Eos incidunt debitis tenetur rerum, esse ratione quisquam possimus quasi nam.</p>
<button>Toggle Content</button>
</div>
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis sed, dicta quasi in blanditiis nam atque odio, nobis a. Eos incidunt debitis tenetur rerum, esse ratione quisquam possimus quasi nam.</p>
<button>Toggle Content</button>
</div>
</div>
jsFiddle

count no of spans of specific class within a dynamically generated div

Supposing I have a number of divs that are dynamically generated and contain text. Each of these divs have a unique id which is also dynamically generated, e.g.
<div id="abstract_12345"> ... text ...</div>
Now within those divs there are spans of a particular type that have been dynamically generated according to a regex, e.g. when the word "significant" is encountered it is tagged as
<span class="emphasis">significant</span>
This is being done via mark.js
What would be a suggestion for a javascript function to enable counting the spans within each div with the aim of placing the count value in an element associated with that div?
Using jQuery you can do:
$('div[id^="abstract_"]').each(function () {
var $this = $(this),
len = $this.find('span.emphasis').length;
console.log($this.attr('id'), len);
});
div {margin: 0 0 15px 0;}
span.emphasis {color: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="abstract_12345"><span class="emphasis">Lorem ipsum</span> dolor sit amet, consectetur adipisicing elit. <span>Sapiente ipsam animi</span>, alias harum aut est unde voluptates repudiandae vel molestias <span class="emphasis">significant</span>, officia! Illum dolore pariatur sequi magnam minus, aliquid voluptate officia, <span>quaerat</span> sint quam <span class="emphasis">commodi</span>.</div>
<div id="abstract_12346">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente ipsam animi, alias harum aut est unde voluptates repudiandae vel molestias, officia! Illum dolore pariatur sequi magnam minus, aliquid voluptate officia, <span>quaerat</span> sint <span class="emphasis">quam commodi</span>.</div>
If you want to do using plain Javascript.
function myFunction() {
var i;
var x = document.querySelector("[id^=abstract_]").querySelectorAll("span");
for (i = 0; i < x.length.i++){
x[i].id = i;
}
}
This code will add id to each span as the index of the span inside the div with id=abstract_12345.
This should do the trick, if I understand your wish correctly.
$('id*="abstract_"').each(function() {
var amount = $(this).find('span.emphasis').length;
$(this).prepend(amount);
});

How can I select specific strings and some with jQuery?

I'm creating a Chrome Extension that will scan through web pages looking for email addresses with a specific domain. In this example, we will use #xyz.com as the domain.
In my content script script.jsand hard coded HMTL page index.html I have the following:
$(document).ready(function() {
$('body:contains("#xyz.com")').css("text-decoration", "underline");
});
.container {
margin: 0 auto;
display: block;
padding: 10px 10px;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.0.0-alpha1.js"></script>
<meta charset="utf-8">
<title>my page</title>
</head>
<body>
<div class="container">
<h1>Welcome!</h1>
<br>
<div class="text-container">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum JohnJones.#xyz.com
, consectetur adipisicing elit. Eos, doloribus, dolorem iusto blanditiis unde eius illum consequuntur neque dicta incidunt ullam ea hic porro optio ratione repellat perspiciatis. Enim, iure! Lorem ipsum dolor sit amet, consectetur adipisicing
elit. Error, nostrum, aliquid, animi, ut quas placeat totam sunt tempora commodi nihil ullam alias modi dicta saepe minima ab quo voluptatem obcaecati? Lorem ipsum dolor sit amet, consectetur adipisicing elit. Harum, dolor quis. Sunt, ut, explicabo,
aliquam SarahBrown.#xyz.com tempore quidem voluptates cupiditate voluptas illo saepe quaerat numquam recusandae? Qui, necessitatibus, est!</p>
</div>
</div>
</body>
</html>
I'm trying to select only the email addresses but this clearly doesn't work since it selects everything.
How can I select text matching my keyword (domain) and then further select characters to the left of it to capture the name until it hits a space or an illegal character an email address couldn't use?
This is problematic because this Extension will run on different pages so it's impossible to tell what element text will be nested in for 100% success rate.
Regex is confusing at first but it is the best option for something like this.
Here is the regex I use for detecting emails
[\w|._%+-]*#xyz.com
To break it down, "\w" matches any word character. "|" means "or" and "._%+-" are other characters that could be used in an email. "*" after brackets means any number of characters that match the contents of the brackets. The rest is exactly what it looks like.
Regex code is designated by putting a "/" before and after the code and the "g" at the end tells it to match multiple values.
You can find out more about how the replace command works here.
See a working example using your code below:
var emailPattern = new RegExp(/[\w|._%+-]*#xyz.com/g);
var el = document.getElementsByTagName("p")[0];
el.innerHTML = el.innerHTML.replace(emailPattern, "<u>$&</u>");
.container {
margin: 0 auto;
display: block;
padding: 10px 10px;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.0.0-alpha1.js"></script>
<meta charset="utf-8">
<title>my page</title>
</head>
<body>
<div class="container">
<h1>Welcome!</h1>
<br>
<div class="text-container">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, tenetur natus doloremque laborum quos iste ipsum rerum obcaecati impedit odit illo dolorum ab tempora nihil dicta earum fugiat. Temporibus, voluptatibus. Lorem ipsum JohnJones.#xyz.com
, consectetur adipisicing elit. Eos, doloribus, dolorem iusto blanditiis unde eius illum consequuntur neque dicta incidunt ullam ea hic porro optio ratione repellat perspiciatis. Enim, iure! Lorem ipsum dolor sit amet, consectetur adipisicing
elit. Error, nostrum, aliquid, animi, ut quas placeat totam sunt tempora commodi nihil ullam alias modi dicta saepe minima ab quo voluptatem obcaecati? Lorem ipsum dolor sit amet, consectetur adipisicing elit. Harum, dolor quis. Sunt, ut, explicabo,
aliquam SarahBrown.#xyz.com tempore quidem voluptates cupiditate voluptas illo saepe quaerat numquam recusandae? Qui, necessitatibus, est!</p>
</div>
</div>
</body>
</html>
If you need to match other domain's emails you can use this Regex instead:
[\w|.%+-]*#\w*.[\w|.%+-]*\b

How to make accordion tabs in different color when active

I need to design accordion in the following way... http://jsfiddle.net/gmcLnowa/1/ as shown on fiddle.
I need to two things to be fixed.
One: How to keep first Tab open by default.
Second: How to show each active tab in different colour when that particular tab contents are active or visible.
Let us say when active
Example One: In Blue colour
Example Two: in red colour
Example Three: In yellow colour.
<div id="accordion">
<ul>
<li>
Example one
</li>
<li>
Example two
</li>
<li>
Example three
</li>
</ul>
<div id="one" class="accordion">
ONE Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet in laborum praesentium esse aliquam molestiae animi non facilis perspiciatis corporis ad molestias quo harum suscipit ipsum incidunt ea voluptates accusantium.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet in laborum praesentium esse aliquam molestiae animi non facilis perspiciatis corporis ad molestias quo harum suscipit ipsum incidunt ea voluptates accusantium.
</div>
<div id="two" class="accordion">
TWO Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet in laborum praesentium esse aliquam molestiae animi non facilis perspiciatis corporis ad molestias quo harum suscipit ipsum incidunt ea voluptates accusantium.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet in laborum praesentium esse aliquam molestiae animi non facilis perspiciatis corporis ad molestias quo harum suscipit ipsum incidunt ea voluptates accusantium.
</div>
<div id="three" class="accordion">
THREE Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet in laborum praesentium esse aliquam molestiae animi non facilis perspiciatis corporis ad molestias quo harum suscipit ipsum incidunt ea voluptates accusantium.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet in laborum praesentium esse aliquam molestiae animi non facilis perspiciatis corporis ad molestias quo harum suscipit ipsum incidunt ea voluptates accusantium.
</div>
</div>
You can trigger a click on the first anchor on ready() to show the first accordian by default: Note that you should trigger it on the native element rather than the jQuery element.
JS:
$("a").click(function(){
$(".active").removeClass("active");
$(this).addClass("active");
})
$("a:first")[0].click()
CSS:
a[href="#one"].active{
background:blue !important;
}
a[href="#two"].active{
background:red !important;
}
a[href="#three"].active{
background:yellow !important;
}
Demo
this is possible with jQuery
Example one
chage color of custom color attribute that you want
$('#accordion a').click(function(){
$('#accordion a').css('backgroundColor','transparent');
$(this).css('backgroundColor',$(this).attr('colr'));
});
fiddle
You should alter your HTML to get this effect.
Added CSS:
#accordion div#one.accordion:target + a {
color: blue;
}
#accordion div#two.accordion:target + a {
color: red;
}
#accordion div#three.accordion:target + a {
color: yellow;
}
Altered HTML: (example)
<div id="accordion">
<ul>
<li>
<div id="one" class="accordion">ONE.......</div>
Example one
</li>
<li>
<div id="two" class="accordion">TWO.........</div>
Example two
</li>
<li>
<div id="three" class="accordion">THREE........</div>
Example three
</li>
</ul>
</div>
Working Fiddle
For the first problem, I guess the only thing you can do is to append the hash #one to your page url or to use jQuery.
For the second problem, you can add this to your css:
#one {
border-color: #C00;
}
#two {
border-color: #FF0;
}
#three {
border-color: #CF0;
}

Dynamically and completely fill a div with placeholder text in javascript

I would like to Fill a div with placeholder text.
I have a div that is 100% width+height. Due to many form factors this height and width will be changing based on the users resolution. How can i dynamically fill that div with lorem ipsum. Also how would i recalculate if window sizes changes? I know i could manually do this with copy paste and overflow hidden but I would rather achieve this in javascript
JSFiddle
css
html,body {
/*background:#edecec;*/
height: 100%;
}
.block-text{
text-align: justify;
font-size: 8px;
font-color: rgba(88,89,91, 1);
font-family: georgia;
line-height: 7px;
}
html
<div class="block-text">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempore, eius, ab, molestiae praesentium hic quia quaerat culpa quas consectetur dolor veritatis vel voluptas minus laborum minima quis dolorum necessitatibus tempora.
</p>
</div>
http://jsfiddle.net/h54tP/1/
var bool = true;
var maxHeight = $('.block-text').height();
do {
$('.container').append("<p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempore, eius, ab, molestiae praesentium hic quia quaerat culpa quas consectetur dolor veritatis vel voluptas minus laborum minima quis dolorum necessitatibus tempora. </p>");
if ($('.container').height() > maxHeight) bool = false;
} while (bool);
Here, as described in my comment. One wrapping element insinde your text box, the block-text set to 100% height and a small while loop do the trick.
Small note: This will not do anything when the window is resized. For that, however, you could just call that entire code inside a window-size-change function.
Also, this allows the text to be slightly larger than the screen. If you want it slightly smaller instead, just do
$('.container').children().last().hide();
in the "if"-clause.
I realize you wanted to solve this with javascript, but have you considered using css psuedo-elements with content? If this is just for placeholder text as you develop I think it will do what you want without having to add a bunch of javascript and fiddle with resize events.
.block-text>p:after {
content: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempore, eius, ab, molestiae praesentium hic quia quaerat culpa quas consectetur dolor veritatis vel voluptas minus laborum minima quis dolorum necessitatibus tempora.';
}

Categories

Resources