I am working on some data buttons but can't figure out how to get the function working. I'm trying to add a class to an element via a data-attribute and a corresponding ID. I then want to stop the event propagation with the button inside the subject.
So far this is what I have:
HTML:
<div class ="subject" id="subject1">
<button class="remove">Remove</button>
The Subject
</div>
<div class ="subject" id="subject2">
<button class="remove">Remove</button>
The Subject 2
</div>
<div class ="subject" id="subject3">
<button class="remove">Remove</button>
The Subject
</div>
<button class="trigger" data-subject="subject1">Trigger</button>
<button class="trigger" data-subject="subject2">Trigger</button>
<button class="trigger" data-subject="subject3">Trigger</button>
CSS:
.active {
color:red
}
JS:
var subject = document.querySelector('.subject');
var trigger = document.querySelector('.trigger');
var remove = subject.querySelector('.close');
var data = trigger.getAttribute("data-subject");
var datajs = (function () {
function init() {
[].forEach.call(trigger),function(btn) {
btn.onclick = function() {this.classList.add("active");}
});
remove.addEventListener('click', function (ev) {
ev.stopPropagation();
removeModalHandler();
});
});
}
init();
})();
and here's a fiddle: http://jsfiddle.net/tNS62/1/
My JS isn't that great as you can probably see.
Try this. First we select all the buttons :
var triggers = document.querySelectorAll('.trigger');
var removes = document.querySelectorAll('.remove');
Then we apply the behavior on each button :
for (var i =0; i < triggers.length; i++) {
var btn = triggers[i];
btn.addEventListener('click', function () {
var id = this.dataset.subject;
document.querySelector('#' + id).classList.toggle('active');
}, false);
}
Use dataset to get the id attached to, then search the corresponding element in order to toogle the active class.
I made the same thing for the remove buttons.
Related
The assignment is to create a click event that will cause the headers to slide up, I am trying to accomplish this task with only one click event reference however this will only work on the first header. Is there a was to accomplish this with out multiple click events?
<h1 id="h1">Heading-1</h1>
<h2 id="h2">Heading-2</h2>
<h3 id="h3">Heading-3</h3>
<div id = "result"></div>
<script src="jquery.js"></script>
<script>
var i= 1;
$("h" + i).bind('click', function () {
var thisID = '#h' + i;
$(thisID).slideUp("slow");
i++;
});
Try to use class instead of ID. Something like
<h1 id="h1" class="sliderHeading">Heading-1</h1>
<h2 id="h2" class="sliderHeading">Heading-2</h2>
<h3 id="h3" class="sliderHeading">Heading-3</h3>
If you need only header that was clicked on to slide up:
$(".sliderHeading").bind('click', function () {
var thisID = $(this).attr('id');
$(thisID).slideUp("slow");
});
If you need all headers to slideup on one click:
$(".sliderHeading").bind('click', function () {
$(".sliderHeading").slideUp("slow");
});
You could try adding a class to all of them and use that in your script.
Try to do it inside the loop, if the number of headers (id) is known.
for (var i=1; i<=3; i++) {
$("h" + i).bind('click', function () {
var thisID = '#h' + i;
$(thisID).slideUp("slow");
});
}
I'm trying to Select one instance of messageCase and expand it. This is the jquery and javascript that I have so far. right now this changes every instance of messageCase and adds the animation properties i want. How can I make it so this does not happen to all instances of messageCase?
also I am under "use strict"; conditions.
$(document).ready(function () {
var aTag = $("div.messageCase").id();
var divTarget = $("div.messageCase")
$(document).click(function (e) {
var target = $(e.target);
if (target.is(aTag)) {
if (divTarget.hasClass("messageCase")) {
// divTarget.removeClass("messageCase");
divTarget.addClass("messageCase messageCaseAnimation");
}
} else {
divTarget.addClass("messageCase");
}
if (!target.is(divTarget))
{
$(divTarget).removeClass("B");
}
});
});
Thanks!
In your click method you assign the clicked element to target, so it appears you could do:
target.addClass("messageCase messageCaseAnimation");
Here's a simplified example of your code:
$(document).ready(function() {
var divTarget = $("div.messageCase")
$(document).click(function(e) {
var target = $(e.target);
target.addClass("messageCase messageCaseAnimation");
});
});
And here's a full demo:
$(document).ready(function() {
var divTarget = $("div.messageCase")
$(document).click(function(e) {
var target = $(e.target);
// Remove the messageCaseAnimation from all
divTarget.removeClass('messageCaseAnimation');
// Add the messageCaseAnimation to only the clicked
target.addClass("messageCaseAnimation");
});
})
.messageCaseAnimation {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="messageCase">
Case 1
</div>
<div class="messageCase">
Case 2
</div>
<div class="messageCase">
Case 3
</div>
<div class="messageCase">
Case 4
</div>
I've got some javascript which I want to be executed and change a list element when a button is clicked:
<button id="click-me" type="button">
<img src="https://cdn4.iconfinder.com/data/icons/basic-ui-elements/700/07_plus-128.png" alt="Add to Event" style="width: 50px"/>
</button>
<div>
<p>Meeting Participants:</p>
<ol id ="list">
</ol>
</div>
Javascript/JQuery:
var List = document.getElementById('list');
$(function (){
$("#click-me").click(function (e){
e.preventDefault();
document.getElementById('list').style.backgroundColor = "green";
var entry = document.createElement("li");
var testText = document.createTextNode("test")
entry.appendChild(testText);
List.appendChild(entry);
return false;
});
});
The background colour is successfully turned green, but no list element can be seen to be added. Why isn't my code working? Thanks
just put List initialization inside click event handler
$(function (){
$("#click-me").click(function (e){
e.preventDefault();
var List = document.getElementById('list');
document.getElementById('list').style.backgroundColor = "green";
var entry = document.createElement("li");
var testText = document.createTextNode("test")
entry.appendChild(testText);
List.appendChild(entry);
return false;
});
});
A jQuery implementation, as you're already using the library:
$(function (){
$("#click-me").click(function (e){
$('#list').prepend('<li>test</li>').css('background-color', 'green');
return false;
});
});
https://jsfiddle.net/nc9guq2r/
I am trying to toggle visibility of signup and signin boxes if sign in and sign up buttons are clicked. I am trying to use only pure javascript.
I wrote simple html and javascript as below:
<div>
<button class="signin">sign in</button><button class="signup">sign up</button>
<div class="signin-box" style="display: none;">
<form class="signin-form">
<label>username<input></label><label>password<input></label><button type="submit">signin</button>
</form>
</div>
<div class="signup-box" style="display: none;">
<form class="signup-form">
<label>username<input></label><label>password<input></label><button type="submit">signup</button>
</form>
</div>
</div>
javascript part:
var signupButton = document.getElementsByClassName('signup')[0];
var signinButton = document.getElementsByClassName('signin')[0];
var signupBox = document.getElementsByClassName('signup-box')[0];
var signipBox = document.getElementsByClassName('signin-box')[0];
console.log("box: ", signupBox, "button: ",signupButton);
var toggleVisible = function(item){
if (item.style.display === 'none'){
return item.style.display = 'block';
}else{
return item.style.display = 'none';
}
};
window.onload = function(){
signupButton.onclick = toggleVisible(signupBox);
signinButton.onclick = toggleVisible(signipBox);
};
The problem here is that the javascript toggleVisible is automatically activated even if i never clicked the buttons.
as a result, the signin-box and signup-box both gets display:block property.
How do i solve this problem?
You're calling the function, not passing it in. Just wrap your function call in an anonymous function:
signupButton.onclick = function() {
toggleVisible(signupBox);
};
If you don't care about older browsers, you can also simplify your code a little if you put your JavaScript at the bottom of the <body> tag and add a rule to your CSS:
document.querySelector('.signup').addEventListener('click', function() {
document.querySelector('.signup-box').classList.toggle('hidden');
}, false);
document.querySelector('.signin').addEventListener('click', function() {
document.querySelector('.signin-box').classList.toggle('hidden');
}, false);
And the CSS:
.hidden {
display: none;
}
I would recommend to use a standard JavaScript method addEventListener() to attached onclick event listener to the button.
It has following advantages over different solution:
You can attach an event handler to an element without overwriting existing event handlers.
You can add many event handlers of the same type to one element, i.e
two "click" events.
In your code it will look like
window.onload = function(){
signupButton.addEventListener("click", function() { toggleVisible(signupBox); });
signinButton.addEventListener("click", function() { toggleVisible(signipBox); });
};
Current code invokes toggleVisible(..) method and assigns its result to the button attribute, which is not one would expect.
signupButton.onclick = toggleVisible(signupBox);
I have a bunch of product buttons like:
<button class='prd-class' data-prd-id='1'>
Product 1
</button>
<button class='prd-class' data-prd-id='2'>
Product 2
</button>
And I have a button click function like so:
$('.prd-class').click(function(){
$('.prd-class').removeClass('cls-focus'); //remove any focused product
$(this).addClass('cls-focus'); //then focus on the selected one
$('#selected-prd-name').text($(this).data('prd-name'));
... etc
});
As you can see, it uses this object reference inside the function heavily.
Now there is another situation where at page load I want the lines inside this function to be executed.
Since there are multiple product buttons, I want to ensure that the I am simulating the click event of the required one.
$(document).ready(function()
{
$("button[data-prd-id='"+prd_id+"']").click();
});
But this does not work. How can I change the code to execute the code lines correctly?
I am not sure about your requirements. However, this demo might give you some ideas to resolve your issues.
HTML:-
<button class='prd-class' data-prd-id='1'>Product 1</button>
<button class='prd-class' data-prd-id='2'>Product 2</button>
<div>
Selected Product ID: <span id="selected-prd-name"></span>
</div>
CSS:-
.cls-focus {
border: 1px solid red;
background-color: brown;
}
JavaScript:-
(function () {
var $prdClass = $('.prd-class'),
$selectedPrdId = $('#selected-prd-name'),
prdClassClickHander = function () {
var $self = $(this);
$prdClass.removeClass('cls-focus');
$self.addClass('cls-focus');
$selectedPrdId.text($self.data('prd-id'));
},
init = function () {
$prdClass.on("click", prdClassClickHander);
};
$(document).ready(init);
}());
// Simulate the click on DOMReady
$(document).ready(function () {
var prd_id = 1;
$("button[data-prd-id='" + prd_id + "']").trigger('click');
});
JSFiddle Demo:-
http://jsfiddle.net/w3devjs/e27jQ/