How to find div that has matching data attr then remove class - javascript

Here is my attempt that doesn't seem to be working:
$('container').find("[data-slider='" + one + "']").removeClass('hidden');
Here is the full function that is wrapped in a document. ready function
$("#service-icon").on('click', function(){
var $this = $(this);
event.preventDefault();
$this.addClass('ease-transition').toggleClass('active-slider-btn');
$(".page-wrapper").find("[data-slider='" + one + "']").toggleClass("hidden");
});
The error that I am getting is:
"Uncaught ReferenceError: one is not defined"

Things to check:
Is `container` a class or id? If so you'll need to add a `.` or `#` respectively
That the expression in the `.find()` function returns what you're expecting
Can you post a link to a JSFiddle or something?
I have a working example here that is similar to your situation.
HTML
<div class="container">
<div data-slider="1" class="hidden">1</div>
<div data-slider="2">2</div>
</div>
<button id="show-1">show slider 1</button>
CSS
.hidden {
display: none;
}
JavaScript
var one = "1";
$("#show-1").click(function(e){
$(".container").find("[data-slider='" + one + "']").removeClass("hidden");
});

Something like this has to work:
$('.page-wrapper').find("[data-slider='" + one + "']").removeClass('hidden');
See it working here: http://jsfiddle.net/sNp7x/2/
Maybe the data attribute is set via javascript as well, so you have to be aware of the timing?!

Related

How to use the title attribute of a div to add a class?

I'm trying to add a class to a div by using the title attribute. Currently the alert is correct. However the class isn't added.
JS Part:
function index(clicked_id){
alert(clicked_id);
$('#sticky').attr("title", +clicked_id).addClass("glow");
}
HTML Part:
<div id="sticky" class="" title='sticky1' onclick='index(this.title)'</div>"
I don't know if I got your question right but I understood that you want to filter|find you div by the title. So maybe this code will help you:
function index(clicked_id){
alert(clicked_id);
$('#sticky [title="' + clicked_id + '"]').addClass("glow");
}
This is how I would do it:
$("[title*='sticky']").click(function(){
$(this).addClass("glow");
});
Here is the JSFiddle demo
Why do you need to do it like that? Can't you just set the class on the element clicked?
JavaScript
function index(el){
$(el).addClass("glow");
}
HTML
<div id="sticky" onclick='index(this)'></div>
Instead just pass this:
onclick='index(this)'
now in the function:
function index(el){
var e = $(el).attr('title');
$('#sticky[title="'+e+'"]').addClass("glow");
}
As the element itself is the target one then just use this:
function index(el){
$(el).addClass("glow");
}
or better to go unobtrusive, remove the inline event handler and use this way:
$('#sticky').on('click', function(e){
$(this).addClass("glow");
});
js at Question returns expected results. Missing closing > at html #sticky <div> tag at
onclick="index(this.title)"
following onclick attribute . Additionally,
+
should be removed at
+clicked_id
at .attr() setting title . javascript + operator attempting to convert clicked_id String to Number when placed before string
function index(clicked_id){
alert(clicked_id);
$('#sticky').attr("title", clicked_id).addClass("glow");
}
.glow {
color: purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="sticky" class="" title="sticky1" onclick="index(this.title)">click</div>

How do I execute a javascript function from an HTML element and send that elements name without use its name specifically?

If there is an answer to this question out there I can not find it.
I have the following function in JavaScript and need to be able to reuse it over and over.
function ParentService_load(_Object) {
$(_Object.parent.parent).jqxDropDownButton({
...
});
$(_Object).jqxGrid({
...
});
$(_Object).bind('rowselect', function(event) {
...
var row = $(_Object).jqxGrid('getrowdata', args.rowindex);
...
$(_Object.parent.parent).jqxDropDownButton('setContent', dropDownContent);
if (row["servicename"].toString().toLowerCase() === "new") {
$(_Object.parent.parent).jqxDropDownButton('close');
...
}
});
}
<div id="jqxParentServiceDropdownButton">
<div id='jqxParentServiceDropdownWidget' style="font-size: 13px; font-family: Verdana; float: left;">
<div id="jqxParentServiceDropdownGrid" onload="ParentService_load(this);"></div>
</div>
</div>
I haven't found a definitive way to call a javascript or jquery function from an element and have that function use that elements' name, etc... So how would I accomplish this?
If by "name" you mean id, then within your function, you can access that as _Object.id. Because you're passing this in your onload=... (but see below), that's a reference to the element on which the event occurred. Within the function, you're receiving that argument as _Object, so you can use the properties on _Object to access information about the element, including its id.
But note that div elements don't have a load event. Also, div elements don't have a parent property; you may be thinking of parentNode.
I'm not completely sure what you are asking, so here are a bunch of examples about returning values embedded in the HTML from a function;
$(document).ready(function(){
$(".lw").click(function() {
alert("Class:" + $(this).attr("class") +
"\nID:" + $(this).attr("id") +
"\nData:" + $(this).data("test") +
"\nName:" + $(this).attr("name") +
"\nTagname:" + $(this).prop("tagName"));
alert($(this).parent().prop("tagName"));
});
});
http://liveweave.com/CZSYqW
Clicking on either of the <p> elements returns a different value in an alert box.

How to retrieve id from selected item using "this"

I am new at jQuery/javascript. I tried some suggestions I found on this forum but so far it did not help.
THis is what I am trying:
When loading categories from a database ( using ajax) this HTML statement is added for each category:
$("#Links ul").append('<li id=\"cat' + i + '" data-catid=' + i + '>' + categorie_tekst[1] + '</li>');
Using F12 I see that the lines are correctly added.
E.g. <li id="cat3" data-catid="3">Seafood </li>
Next step is selecting a category in the screen and retrieve the products of this category using the value set for data-catid.
I have been told that I could "this.id" but so far no luck. Displaying the value of this.id with alert returns the correct value but for some reason I can't use it.
When I add (#cat3).attr(“data-catid”) in the code it works. But different options like these did not work:
("#cat"+ this.id).attr(“data-catid”)
(this).attr(“data-catid”)
var x = $(this).id();
var rest = x.substr(4, 1);
Everything with "this" creates error : Uncaught TypeError: ("#cat" + this.id).attr is not a function...
Trying to display any of these options does not give any output (not even a popup when I set an alert)
Any help would be appreciated!
You are loading dynamic values. Please use Event Delegation. And the $.one() binds the event once.
You need to add this in your ready function.
$(document).ready(function () {
$("#Links ul").one("click", ".cat", function(){
alert($(this).data('catid'))
});
});
To get the IDs of the elements, use $(this).attr("id") or $(this).prop("id") (latest jQuery) instead of this.id, as sometimes, it might return the jQuery object.
As you are creating elements like
$("#Links ul").append('<li class="cat" id=\"cat' + i + '" data-catid=' + i + '>' + categorie_tekst[1] + '</li>');
create elements using jQuery
$("#Links ul").append( $('<li></li>', {
class: "cat",
id: "cat" + i,
data-catid: i,
text: categorie_tekst[1]
});
As you are creating elements dynamically use Event Delegation. You have to use .on() using delegated-events approach.
$(document).ready(function () {
$("#Links ul").on(event, ".cat", function(){
alert($(this).data('catid'))
});
});

How to set cookie onclick for changing background

I try to change the background of a div onclick and preserved it with a cookie. Here is my code. Firstly I can't realize if my cookie has been set and secondly if I can change the background with the value of the cookie.
Can anyone help with an idea?
<div class="container">
<div class="col-md-6">
<div class="one"><a id="1" onClick="addcookie()" href="#">Fisrt Link</a></div>
</div>
<div class="col-md-6">
<div class="two"><a id="2" onClick="addcookie()" href="#">Second Link</a></div>
</div>
</div>
<script src=js/jquery-1.11.1.js></script>
<script src="js/jquery.cookie.js"></script>
<script>
var cookieName = 'cookie1';
function addcookie(){
var date = new Date();
var minutes = 5;
date.setTime(date.getTime() + (minutes * 60 * 1000));
var idi = getDocumentById(this.id);
var cookieValue = "http://path to image/image"+idi+".png";
$.cookie(cookieName, cookieValue, { expires: date });
$('.one').css('background', $.cookie('cookieName'));
}
</script>
<script src=js/bootstrap.js></script>
</body>
Other than what #George already pointed out in a comment (replace getDocumentById() - non-existent native function - with document.getElementById()), you'll also have to make sure that you're adding the image URL is coded properly, os instead of...
$('.one').css('background', $.cookie('cookieName'));
...do this...
$('.one').css('background', 'url("' + $.cookie(cookieName) + '")');
This is the proper CSS syntax for including background URL's is not...
background:http://path to image/image.png
...but...
background:url("http://path to image/image.png");
...and because if you want to use a variable as a function's parameter, you have to omit the quotes around it, ie. $.cookie('cookieName') becomes $.cookie(cookieName).
Additionally, this.id will only return the id of the element if you pass this as a parameter of your inline function as follows:
onClick="addcookie(this)"
...then reference the same in your function like this:
function addcookie(that)
...and use it like this:
var idi = that.id;
Here is a jsfiddle where you can try this: http://jsfiddle.net/yxj8w6d0/
EDIT: With a few little modifications (remove the one and two classed divs, and add no-repeat to the background) you have a neat little way of always only adding the background to the element in question, assuming it's what you actually wanted to achieve: http://jsfiddle.net/yxj8w6d0/1/
EDIT #2: To get the images loaded if the cookie already exists, create another function that fires on document ready going through your links and checking them against the existing cookies, as follows:
$(document).ready(function() {
$('.container div a').each(function(){
if ($.cookie(this.id))
$(this).css('background', 'url("' + $.cookie(this.id) + '") no-repeat');
});
});
I updated the above fiddle accordingly. Try it by clicking the links first, then running the script again - you'll see that the links will keep their background: http://jsfiddle.net/yxj8w6d0/2/

jQuery toggle() text in separate element

I am having some trouble getting a toggle function to work and need someone to help explain it to me.
My HTML (simplified):
<div id="filter_names"></div>
<div class="item">Option 1</div>
<div class="item">Option 2</div>
<div class="item">Option 3</div>
<div class="item">Option 4</div>
My jQuery (simplified)
$(".item").click(function(){
var tagname = $(this).html();
$('#filter_names').append(' > '+tagname);
$(".loading").show();
});
As you can see I am appending clicked items' value to the div at the top. This works fine, but i need it to be removed when i click it again.
I am pretty sure it needs a toggle() function but so far my attempts have been pretty fruitless.
Some guidance would be greatly appreciated.
EDIT: You can see what i want to achieve in this JSfiddle. It's working exactly how i want it to by appending a value to the end (like a breadcrumb link), but is not being removed when i click it again.
You need to look at the #filter_names contents and check if the clicked tag's value is already included, then remove it if it is, or add it otherwise:
if (filternames.indexOf(tagname) === -1) {
$('#filter_names').append(' > '+tagname);
} else {
$('#filter_names').text(filternames.replace(' > '+tagname, ''));
}
Working fiddle: http://jsfiddle.net/passcod/Kz3vx/
Note that you might get weird results if one tag's value is contained in another's.
<script type="text/javascript">
$(function(){
$(".item").click(function(){
var $this=$(this);
var tagname = ' > ' +$this.html();
//if has item-check class remove tag from filter_names
if($this.hasClass("item-click")){
var h=$("#filter_names").text();
$("#filter_names").text(h.replace(tagname, '' ));
}
else{
$('#filter_names').append(tagname);
}
$(this).toggleClass("item-click").toggleClass("item");
});
});
</script>
try this one...
$(this).toggleClass("item-click item");
this will add these classes alternatively when you click on div. or if you just want to remove this class on second click then you should write this in your click handler.
if( $(this).hasClass("item-click")){
$(this).removeClass("item-click");
}
EDITED -----
to remove appended html you can try this...
if($(this).hasClass("item-click")){
$("#filter_names").text("");
}
else{
$('#filter_names').append(tagname);
}
it's working HERE
hope this helps you!!
I like passcod's solution - here's an alternative that wraps the elements in divs and puts them in alphabetical order.
JSFiddle here. The sort function is from http://www.wrichards.com/blog/2009/02/jquery-sorting-elements/.
$(".item").click(function(){
var tagname = $(this).html();
var target = $('#filter_names').find('div:contains("> ' + tagname + '")');
if (target.is('*')) {
target.remove();
}
else $('#filter_names').append('<div class="appended"> > '+ tagname +'<div>');
function sortAlpha(a,b) {
return a.innerHTML > b.innerHTML ? 1 : -1;
}
$('#filter_names div').sort(sortAlpha).appendTo('#filter_names');
});

Categories

Resources