Localstorage getitem - match to div class - html

So I have created a simple code, so when the user clicks a child div of 'speaker-cookie' parent, they then set a localstorage value. Code is:-
$(".speakers-cookie div").on( "click", function() {
var speakerpop = $(this).attr("class");
localStorage.setItem('speaker', speakerpop);
});
This is working well, when on another page I want to get the value for the speaker and test IF the value matches a div, then change the colour of the div. I have tried the following:-
<script>
var speakercolor = localStorage.getItem("speaker");
$('body').find(speakercolor).css('background','red')
</script>
Could someone please advise what I am doing wrong here? This is not colouring the div atall.
Thank you

Related

Having trouble with jquery dynamic input and regex matching. Partially works

I have a dynamic input field where a user can add as many colors as he wants using an "Add" button.
The array works fine. Posts fine. My issue is with a some regex matching. Basically if a user enters one of the colors in the regex pattern a div container with another input shows. This works fine.
The issue:
User enters "purple" - no match, nothing shows. Good.
User enters "blue" - match, div shows. user deletes "blue" div disappears. Good.
User enters "red" - match, div appears. Good.
User enters "yellow" - no match, div disappears. Not Good.
Once the match has occurred I need the div to stay visible. What's happening though is it's removing the div if the next input is not a match.
$("#add").click(function(e){
$('input[name="item_color[]"]').keyup(function() {
var data = $(this).val();
var regx = /(blue|red|orange)/gmi;
if (data.match(regx)){
$("#divcolor").show();
}
else {
$("#divcolor").hide();
}
});
});
I've tried removing the
$("#divcolor").hide();
which somewhat works. except if the user goes back through the inputs and deletes the match that caused the div to show initially the div continues to show.
Basically I just need it to show the div if any match occurs in any of the inputs and hide the div if no matches occur. I really need the div to show/hide on keyup is the biggest thing.
Any help would be appreciated. I'm sure its something easy. I just can't wrap my mind around the logic.
You could solve the issue by checking all inputs each time you call the handler and set a var to true, if there is a match:
let matches = false;
$('input[name="item_color[]"]').each(function() {
if ($(this).val().match(regx)){
matches = true;
}
});
Furthermore the issue, that you mentioned in the comments, that the event handler isn't working when you define it outside the add handler, is related to the fact, that the inputs aren't created at the time of the definition. To prevent it you could attach the event listener directly to the body but add a selector to it:
$('body').on('keyup', 'input[name="item_color[]"]', function() {
Then the event listener is attached to an element that exists and the selector is used not before the listener is called.
Working example:
$("#add").click(function(){
$('#input-wrapper').append('<input name="item_color[]">');
});
$('body').on('keyup', 'input[name="item_color[]"]', function() {
let matches = false;
var regx = /(blue|red|orange)/gmi;
$('input[name="item_color[]"]').each(function() {
if ($(this).val().match(regx)){
matches = true;
}
});
if (matches){
$("#divcolor").show();
}
else {
$("#divcolor").hide();
}
});
#divcolor {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add">Add</button>
<div id="input-wrapper">
<input name="item_color[]">
</div>
<div id="divcolor">
<p>div visible</p>
</div>

How to continue jQuery Function

I am using the following code to change href links in a page to a new link by using their id.
This is what I'm using to find the href and add the id to it;
$( document ).ready(function() {
$('a[href$="/truck-bed-covers/camper-tops"]').attr('id', 'camper1');
});
And this is what I'm using to change the link.
$(document).ready(function () {
$("#camper1").attr("href", "../camper-tops");
});
It works great. Except it doesn't continue on the rest of the page. It only changes one link and then it's done. How do I continue until there is no more links to change?
ID has to be unique, else JavaScript works with the first one only.
$(document).ready(function() {
$('a[href$="/truck-bed-covers/camper-tops"]').each(function(){
$(this).attr("href", "../camper-tops");
});
});
But I don't think this is the right way. You should find place where you create incorrect links and repair it there (in PHP/DB or where links came from).
At a guess, you're adding the ID so you can refer to the element in the second line, but you don't need to. Once you have an element you can work on it.
You can select all links with something like $('a[href]') (all links with an href attribute) and then iterate over all of them with jQuery's each function. Something like
$(function(){ // shorthand for $(document).ready()
$('a[href]').each(function(index, element){
// work on each element here
var $el = $(element);
$el.attr('href', $el.attr('href').replace(/*whatever you want to do here */);
});
});

detecting and hiding dynamically creating div after a specific seconds (not onclick)

i have a dynamically generating div which is not in the time of loading. It is generating later in the document. So how can i target that div and hide it after specific time. The div is as follows:
<div class="message-sent">Your Message has been sent</div>
Important: I refer so many articles but everyone is talking about 'onclick'. I don't want click event. I just want hide this div when it is appearing in the docuemnt. Thanks in advance!
you can add a style display:none.
you can add the style after time out (3000ms) like so:
setTimeout(function(){
document.getElementsByClassName("message-sent")[0].style.display="none";
}, 3000);
note: it is better if you use an id instead of a class to identify your div.
You should try looking into the setTimeout function.
Also if that div is the only member of the DOM-tree that has that class, use an ID. It's better IMO.
Anyway, assuming you want to hide every member of the message-sent-class,
it goes something like this:
setTimeout(function(){
$('.message-sent').hide();
}, 2000)
In which the 2000is the variable that indicates the time (milliseconds)
You can try DOMNodeInserted,
$(document).bind('DOMNodeInserted', function(event) {
var element = document.getElementsByClassName("message-sent"); // get all elements with class message-sent
var lastchild = element[element.length - 1]; // get the last one (others are hidden)
if(lastchild != null){
lastchild.style.visibility = 'hidden'; // set visibility to hidden
}
});
Working demo
Hope helps,

Unable to get div attributes

I am trying to get the attributes for a selected div, when i do alert and the div name, it give me the div name but when i do alert divname.style.backgroundcolor, it gives me an error, undefined. I have noticed that its only when i add the attribute to the selected div, it gives me an error and if i type the name of the div directly with the attribute
it gives me the right answer.
function getdiv(){
var selecteddivname = document.getElementById("divname").value;
alert(selecteddivname); // this works, it shows the divname right
alert(selecteddivname.id); // its shows undefined
alert(selecteddivname.style.backgroundColor); //its shows undefined
alert(moused.style.backgroundColor); //this works, mouse being the actual div name
}
It sounds like you're trying to get at the attributes of a div identified by the input with the id divname.
If so:
function getdiv(){
var selecteddivname = document.getElementById("divname").value;
var selecteddiv = document.getElementById(selecteddivname);
console.log(selecteddivname);
console.log(selecteddiv.id); // should match
console.log(selecteddiv.style.backgroundColor);
console.log(moused.style.backgroundColor);
}
try to use valid attributes for div like this
<script type="text/javascript">
function getdiv(){
var selecteddivname = document.getElementById("divname").id;
alert(selecteddivname); // this works, it shows the divname right
alert(selecteddivname.id); // its shows undefined
alert(selecteddivname.style.backgroundColor); //its shows undefined
alert(moused.style.backgroundColor); //this works
}
</script>
and here the tag
<div id="divname" name="mahmoud" onmouseover="getdiv()" >how are you guys</div>
hope this be helpful

Transverse Html Elements Till a Specifc Attribute (id) using Jquery

I am using Jquery 1.7.2.
I want to transverse Html Elements Till a Specifc Attribute (id) using Jquery on
mouse over on any html element in my page.
we have parents() function but problem is how to select stop on the parent element which has id attribute
$("*", document.body).click(function (e) {
e.stopPropagation();
var domEl = $(this).get(0);
var parentEls = $(domEl).parents()
.map(function () {
return this.tagName;
})
.get().join(", ");
$("b").append("" + parentEls + "");
});
this is code but i am getting all element till root
but i want to stop on a closet elements which has attribute id in the tag
Please help me out .
Just use closest:
$(this).closest('#the-id');
Unless your'e just looking for the closest one that has any id attribute, which would be:
$(this).closest('[id]');
Edit: after seeing your updated question, this should be what you want:
$(document).click(function(e) {
e.preventDefault();
var parents = $(e.target).parentsUntil('[id]')
.map(function() { return this.tagName; }).get().join(',');
console.log(parents);
});
Note that this approach accomplishes what you want without selecting and binding click events to every node in the DOM, which is a pretty heavy handed approach.
Edit (again): looks like maybe you wanted to include the tag with the id attribute on it (the above solution is everything up to, but not including that tag). To do this, the solution is pretty similar:
$(document).click(function(e) {
e.preventDefault();
var $parents = $(e.target).parentsUntil('[id]');
var tagNames = $parents.add($parents.parent())
.map(function() { return this.tagName; }).get().join(',');
console.log(tagNames);
});
It looks like you want to map the hierarchy from the clicked element up to the document root. In that case, you can apply parents() to event.target:
$(document).click(function(e) {
e.preventDefault();
var parentEls = $(e.target).parents().map(function() {
return this.tagName;
}).get().join(", ");
});
Note that, as jmar777, you should also change your selector: "*" adds an event handler to all the elements, which is probably not what you want. Bind a single handler to document instead to take advantage of event bubbling.