I want to update this very simple JS to Mootools 1.2 and it's not easy.
This function :
function changeclass(x){
document.getElementById("content").className = "ziclass0";
document.getElementById("content").className = "ziclass" + x;
}
is triggered in the DOM by :
<div id="someclass">
a href="javascript: changeclass(0)">Unstyled</a
a href="javascript: changeclass(1)">link one</a
a href="javascript: changeclass(2)">link two</a
a href="javascript: changeclass(3)">link three</a
</div>
to call the according CSS classes like :
.ziclass1 h1{
color: rgb(142,11,0);
font-family: Verdana;
font-size: 2.5em;
letter-spacing: 0.1em;
}
and changes the layout accordingly in :
<div id="content" class="ziclass3"> ... </div>
I know I can add an event to the triggers like :
$(#someclass.each(function(element,index) {
element.addEvent('click', function(){
//some code
});
But, how do I get #content class classname ?
Through an array ?
I am a bit confused here.
I'd be really grateful for any help to set me on the right track
These are very basics of MooTools. Anyway, here's how you change a class name of a collection of elements:
$$('#container a').each(function(link){
link.addEvents({
click: function(e){
e.stop();
this.set('class', 'newClassName');
// to append a class
// this.addClass('appendThisClass');
}
});
});
Here's a working example: http://jsfiddle.net/oskar/9fxxr/
It's all in the documentation: http://mootools.net/docs/core/Element/Element
But this is not exactly what i was asking.
The triggering element (a) calls a css element by looping through its number located in "href".
EX :
a href="javascript: changeclass(1)">Link One</a
// calls all CSS classes named .ziclass1 and applies/adds them in "content"
a href="javascript: changeclass(2)">Link Two</a
// calls all CSS classes named .ziclass2 and applies/adds them in "content"
USING
function changeclass(x){
document.getElementById("content").className = "ziclass" + x;
}
RESULT :
HTML:
a href="javascript: changeclass(1)">Link One</a
a href="javascript: changeclass(2)">Link Two</a
<div id="content" class="ziclass1">
...
</div>
That's why I was thinking about an array.
Around this idea :
var myArray = ["0","1","2", etc ...];
function myFunction() {
myArray.each(function(value, index, array){
$(value).addEvent('click',function(event) {
console.log(value);
// add my class here
});
});
};
myFunction();
where I'd get the value of the array located in the href like this :
a href="1">Link one</a
a href="2">Link two</a
and change the class accordingly.
But I dont know how to do this.
Related
Here is the problem
This is my html code
<div id="bookmark">
<i class="far fa-bookmark"></i>
</div>
I want to change .far to .fas and vice versa in loop when clicked.
This is my updated javascript
function changeClass(elem) {
var i = elem.childNodes[1];
var c = i.classList;
console.log(i)
console.log(c)
// Change class
if (c.contains("far")) {
i.classList.remove("far");
i.classList.add("fas");
} else {
i.classList.remove("fas");
i.classList.add("far");
}
}
This is the screenshot of the console output in the browser when I click on the bookmark icon
Screenshot
When I pass the index value in the var c respectively, on i.classList[0] I get svg-inline--fa but I get undefined value in i.classList[3] instead of far. SO WHAT SHOULD I DO?
I hope this is what you are looking for (Demo: https://jsfiddle.net/hwv0oacL/8/)
HTML
<div id="bookmark" onclick="changeClass(this)">
<i class="far fa-bookmark"></i>
</div>
Javascript
changeClass(elem) {
var i = elem.childNodes[0].classList;
// Change class far to fas
if (i.includes("far")) {
i.classList.remove("far");
i.classList.add("fas");
}
// Get back to original state
if (i.includes("fas")) {
i.classList.remove("fas");
i.classList.add("far");
}
}
-------------------Updated--------------------------
Replace the above javascript with the one below. It will also work in loop like you want because we are getting element by this keyword.
JavaScript
function changeClass(elem) {
var i = elem.childNodes[1];
var c = i.classList;
// Change class
if (c.contains("far")) {
i.classList.remove("far");
i.classList.add("fas");
} else {
i.classList.remove("fas");
i.classList.add("far");
}
}
You can do it like below with jQuery:
$("#bookmark").find("i").removeClass("far");
$("#bookmark").find("i").addClass("fas");
assuming you want this to be done for single element and not for all the elements that are using .far class
add an id to the tag like id="i1" then you can add an event listener on that element. listening to the click event and once captured - toggle the class.
add the following just before the end of the body tag i.e. before </body>
<script>
document.getElementById('i1').addEventListener('click', (e) => {
e.target.classList.toggle('far');
e.target.classList.toggle('fas');
})
</script>
I have a tag with below HTML :
<a href='#' class='create_account singup header-icon'>Create Account</a>
I am using a common click handler of the 3 button with Class create_account , member_login , product_service
Now inside the handler , I want the class name which triggered the click event, in best possible way (with minimal condition)
$('.create_account , .member_login , .product_services').click(function(){
console.log($(this).attr('class'));
/**
In case , user click on button with class `create_account` , I get in console
`create_account singup header-icon` , which is correct,
**but I want `create_account` i.e is the class which triggered the Click event**
*/
});
I would just create a separate click handler for each class, like so:
// Define all the required classes in an array...
var selectors = ["create_account", "member_login", "product_services"];
// Iterate over the array
$.each(selectors, function(index, selector) {
// Attach a new click handler per-class. This could be a shared function
$("."+selector).click(function(e) {
e.preventDefault();
alert(selector); // Logs individual class
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="create_account" href="">Create</a>
<a class="member_login" href="">Login</a>
<a class="product_services" href="">Services</a>
If you want you can abstract the shared logic out into another function, like this Fiddle
Alternative Approach with Data Attributes
<a href='#' class='action-trigger' data-action='Creation'>Create Account</a>
$('.action-trigger').click(function(){
console.log($(this).data('action'));
});
Retrieve Class Based on it Being First
<a href='#' class='create_account singup header-icon'>Create Account</a>
$('.create_account , .member_login , .product_services').click(function(){
console.log($(this).attr('class').split(' ')[0]);
});
Alternative Approach with Parameters
<a href='#' class='create_account singup header-icon'>Create Account</a>
$('.create_account').click(function(){
MyFunction('CreateAccount');
});
$('.member_login').click(function(){
MyFunction('MemberLogin');
});
function MyFunction(type)
{
console.log(type);
}
$(this).attr('class');
This will always return the list of classes that the element has. You can actually include an 'id' attribute to the element to access it when clicked.
<a href='#' class='but' id='create_account'>Button 1</a>
$('.but').click(function(){
alert($(this).attr('id'));
});
Demo: https://jsfiddle.net/dinesh_feder/2uq5h03j/
There are good solutions put forth using an array of selectors, but here is a solution using the strings of the selectors and the classes of the triggering element.
It's unfortunate that .selector was removed in jQuery 1.9 or else this would be even simpler. The approach is to get the original selector as an array and intersect it with the array of classes on the triggering element. The result will be the class that triggered the event. Consider this example:
[".create_account", ".member_login", ".product_services"]
[".class1", ".class2", ".create_account"]
Their intersection is:
[".create_account"]
Here is working code:
var selector = '.create_account, .member_login, .product_services';
$(selector).on("click", { sel: selector.split(", ") }, function(e){
var classArr = $(this).attr("class").split(" ").map(function(a){ return "."+a; });
var intersect = $.map(e.data.sel,function(a){return $.inArray(a, classArr) < 0 ? null : a;});
alert(intersect[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="class1 class2 create_account">class1 class2 create_account</button><br/><button class="class3 product_services class4">class3 product_services class4</button><br/><button class="class5 class6 member_login">class5 class6 member_login</button>
I would add the classes into an array and then iterate to it to see if our target has one of those into its class attribute :
var classes = ['.create_account' , '.member_login' , '.product_services'];
$(classes.join()).click(function(){
for(var i=0; i<classes.length; i++){
var classPos = $(this).attr('class').indexOf(classes[i].substring(1));
if(classPos>-1)
$('#result').html(classes[i]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' class='create_account singup header-icon'>Create Account</a>
<a href='#' class='member_login singup header-icon'>Member Login</a>
<a href='#' class='singup header-icon product_services'>product services</a>
<p id="result"></p>
Well, to take back the Manish Jangir .... example, if you have to retrieve only the concerned class, then why don't you test it? you use jquery so you can use "hasClass" don't you?
$('.create_account , .member_login , .product_services').click(function(e){
if($(this).hasClass('create_account')){
alert('create_account');
}
if($(this).hasClass('member_login')){
alert('member_login');
}
if($(this).hasClass('product_services')){
alert('product_services');
}
});
This is maybe not a "perfect solution" but it fits your requirements...^^
You can also do it this way with jquery :
$('body').on('click','.create_account',function(event){
alert('.create_account');
//do your stuff
});
$('body').on('click','.member_login',function(event){
//...
});
$('body').on('click','.product_services',function(event){
//...
});
this way you just have to add a block if you add a new class that needs an event on click on it... I do not see any more "specific" answer to your question... I always used to do it this way since the way I handle the event on classes can be really different...
i am just building a small snippet to hide a div checkout my snippet :
var Modal = function(){
Modal.prototype.hide = function(elem){
return elem.hide();
// i basically want to change the above line to this.hide();
}
}
$(document).ready(function(){
var _str = new Modal();
var div = $('#mydiv');
_str['hide'](div);
});
now , the reason i built this snippet is because i wanted to understand the code in modal.js and how it works , lets checkout the code in modal.js .
checkout this line :
data[option](_relatedTarget)
data is basically an instance of Modal
[option] is basically Modal.prototype.toggle(param)
and (_relatedTarget) is basically the parameter being passed .
so basically whats happening on that line is , the following function is being called .
hide(_relatedtarget).
I console.logged _relatedtarget and found out , it is basically an HTML element , looks something like below :
<a data-target="#myModal" data-toggle="modal" class="btn btn-primary btn-lg">
if you have a look at the toggle function , it looks something like below :
Modal.prototype.toggle = function (_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
so bascially we are passing the following parameter in the above function :
<a data-target="#myModal" data-toggle="modal" class="btn btn-primary btn-lg">
and it all works fine .
Now , lets review th hide function in my code :
Modal.prototype.hide = function(elem){
return elem.hide();
}
see how my hide function differs in the sense that, i am using the following syntax to hide my code :
elem.hide();
whereas the code in modal.js uses the following syntax :
this.hide()
but if i use the above syntax and run my code , the code does't work and the element is not hidden.
so my question is, how can i change the syntax in my code to :
this.hide() and make my code work, Fiddle of my example is here .
Thank you .
Alexander.
For this function to work without a parameter, the div needs to be known by the Modal. You could do it by passing the container's selector to your constructor, like so:
var _str = new Modal('#modal-container');
And assigning it as a property of Modal. Example code:
var Modal = function(containerSelector) {
this.container = $(containerSelector);
Modal.prototype.hide = function() {
return this.container.hide();
}
}
// Using a setTimeout for the demo, so you can see it first
setTimeout(function() {
var _str = new Modal('#modal-container');
_str['hide']();
},1000);
#modal-container {
height: 100px;
width: 100px;
background: #aaa;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This div will hide after 1 second:</p>
<div id="modal-container"></div>
Edit: don't confuse jQuery's hide() function (called on DOM elements) with your own (called on a Modal object). Check this fiddle, it implements a toggle() function just like you have at line 48.
I want to apply cursor: pointer; to any element that has jQuery click() function bound to it.
How can I do this without going to each element in my CSS file and manually adding cursor: pointer; to it? (I have a lot of various clickable items)
<span class = "clickable1">something</span>
<span class = "clickable2">something</span>
<span class = "clickable3">something</span>
$(".clickable1").click(function(){
//do something
});
$(".clickable2").click(function(){
//do something
});
$(".clickable3").click(function(){
//do something
});
You actually can do this.
By checking the internal $._data you can get the bound events on any element, then it's just a matter of checking if click is one of those events and attaching the style etc.
$('*').filter(function() {
var d = $._data( this, "events" );
return d && 'click' in d;
}).css('cursor', 'pointer');
FIDDLE
Add another class called isclickable so you would have
<span class = "isclickable clickable1">something</span>
<span class = "isclickable clickable2">something</span>
<span class = "isclickable clickable3">something</span>
Then you can have .isclickable { cursor: pointer; } in your css
Solution 1: give every clickable element the same class like
<span class = "clickable clickable1">something</span>
<span class = "clickable clickable2">something</span>
<span class = "clickable clickable3">something</span>
Solution 2: expand jQuery selector $(".clickable1, .clickable2, .clickable3")
Why not add a common class to all of them?
<span class = "clickable clickable1">something</span>
<span class = "clickable clickable2">something</span>
<span class = "clickable clickable3">something</span>
Then, with css:
.clickable {
cursor: pointer;
}
If you'd rather not change the HTML you already have manually (or if you can't), you can add the class when binding the event handlers:
function addClickBehavior($el, callback) {
return $el.addClass("clickable").on("click", callback);
}
addClickBehavior($(".clickable1"), function(){
//do something
});
addClickBehavior($(".clickable2"), function(){
//do something
});
addClickBehavior($(".clickable3"), function(){
//do something
});
Simply use a selector that selects all elements whose class name starts with "clickable":
$("*[class^='clickable']").css('cursor', 'pointer').click(function(){
//do something
});
BTW: Seems like a very "inefficient" use of the class attribute and class names aren't very "useful".
I have this code in JavaScript:
function change() {
document.getElementById("mem").className = 'gif';
}
The fig and gif are like this:
a.fig {
background: #FFFFFF;
}
a.gif {
background: #000099 ;
}
and the function is used like this
<a class ="fig" id ="mem" onClick="javascript:change()" href="users" >
Where the only difference between gif and fig in CSS is that they have different background colors. The problem is that the change is only noticeable in just a second and it is not permanent!
Any ideas?
HTML:
<a id="mem" class="fig" href="users"> MEMBERS </a>
JavaScript:
var a = document.getElementById('mem');
a.onclick = function() {
this.className = this.className == 'fig' ? 'gif' : 'fig';
}
Live demo: http://jsfiddle.net/eVQjB/
Note: in the demo, I return false; from the click handler to prevent the anchor from being activated.
function change() {
var mem = document.getElementById("mem");
if (mem.className == 'fig') {
mem.className = 'gif';
}
else {
mem.className = 'fig';
}
}
You may be looking for a different problem with JavaScript and styles, but if I understand your problem, you'll still need a different color for the anchor if it has been visited. You can let CSS do that for you:
#mem {
background: #FFF;
}
#mem:visited {
background: #009;
}
<a id="mem" href="users">Lead me to the promised land!</a>
you can try by following way
document.getElementById("idElement").setAttribute("class", "className");
IF still not working you r class is not chaning the style of your html element
Just add return false:
onClick="change(); return false;"
The thing is that without it, the class is changed then the page is redirected as this is the default behavior of anchor tag.
If you want to reload the page and change the class in the reloaded page, have such link:
href="?change=true"
Then in the server side code check for this flag and if true put different class. I'm not familiar with PHP but here is classic ASP version, hopefully similar enough to PHP:
<%
Dim sClassName
If Request("change")="true" Then
sClassName = "gif"
Else
sClassName = "fig"
End If
%>
<a class ="<%=sClassName%>" id ="mem" href="?change=true">