Know which user created div was clicked - javascript

I apologise if my explanation is hard to understand.
Using This Code:
names.push(newName);
var strName = newName;
var newName = document.createElement('p')
newName.setAttribute('id', newName);
document.body.appendChild(newName);
newName.innerText = strName;
$(newName).css('position','absolute')
$(newName).css('top', y);
$(newName).css('left', x);
updateXY();
The user creates a new div (with a user-inputted name) which works fine.
my problem is that i don't know how to know when one of these user-crated-and-named divs is clicked.
For example:
if the user created 2 divs, 'hello' and 'goodbye' i couldnt just use $('#hello').click(function() {}); etc. Because i wouldnt know that the user would've chose to create the div entitled 'hello'
Furthermore, the array names has all of the names of all of the divs in - if this is any help to anybody. Thankyou, and any help is appreciated

Simply add the event listener to the element as you did when styling it:
$(newName).on("click",function(){
console.log("element "+$(this).text()+" clicked");
});
JSFiddle
Or, with JS's addEventListener():
newName.addEventListener("click",function(){});
JSFiddle
Or, the old way for older browsers, onclick:
newName.onclick = function(){};
JSFiddle

You could do something like this
$(newName).on("click",function(e){
// the variable 'e' is the event of click, if we do e.toElement, we get to know who the element clicked is
var $thisDiv = $(e.toElement);
// do something with $thisDiv
});

After you create a div element, you need to initialize 'click' event on the div
<a class="js-create-div" href="#">Create Div</a>
$(document).ready(function(){
function init(){
var newUserDiv = $(".js-user-div").not(".js-inited");
newUserDiv.on("click",function(){
alert($(this).html());
});
newUserDiv.addClass("js-inited");
}
$(".js-create-div").click(function(){
$("#wrapper").append("<div class='js-user-div'>"+Math.random()+"</div>");
init();
});
});
https://jsfiddle.net/ema0nazs/

Related

Highlight single element in ng-repeat

following problem:
I am using ng-repeat to generate a list of items. If the user clicks on a special marker on my webpage above, the following function receives an event an scrolls down to the corresponding item. In addition to scrolling down I would like to highlight the item until the user moves the mouse again. My problem ist that do to this I need to manipulate the css class of one single element of my ng-repeat list. I thought it might be possible because every ng-repeat element gets its own local scope...but I don't find the solution.
Part of my directive:
//if a marker is clicked, the following code should bring the user to the corresponding item
$rootScope.$on("Scroll_to_product", function (event, args) {
product.gotoElement(args);
});
/*function which takes the class id of an html element as argument and brings
the user to the corresponding product*/
product.gotoElement = function (args) {
var elementID = 'product-' + args;
$location.hash(elementID);
// call $anchorScroll()
$anchorScroll();
}
Any help would be great,
Thanks, Hucho
I think this woking Plunker example may help you
Plunker link
$scope.idSelectedVote = null;
$scope.setSelected = function(idSelectedVote) {
$scope.idSelectedVote = idSelectedVote;
console.log(idSelectedVote);
}
.selected {
background-color: red;
}
<ul ng-repeat="vote in votes" ng-click="setSelected(vote.id)" ng-class="{selected : vote.id === idSelectedVote}">
</ul>
it almost broke my head, but finally was easy:
product.highlightFeature = function (args) {
var id = '#'+ 'feature-' + args;
var myEl = angular.element( document.querySelector( id ) );
myEl.addClass('feature-highlight');
};
It is easy and fast..; yet thanks for your help.
This might help others...
Best
Hucho

$(this) acts like both event and <div>

I'm a long-time procedural programmer now assigned to a web-app and studying jquery from a book. The exercise is to run some code on one div selected from a row of 4 <div>s using .each(). I attempted to store the div object that was clicked, then match it as the .each looped thru the 4 divs.
My following code works after trial and error, but the same $(this) seems to sometimes point to a div object, and sometimes to an event object.
How do you explain that behavior?
I understand that .context is deprecated. I tried .target but that didn't seem to work. Is there something else that I should be using?
My primary interest is to understand what is going on (question 1), so if you can provide an explanation and not just an alternative solution (question 2), I'd really appreciate it. Thank you in advance. Here are the code snippets:
<body>
<div id="header">
<h2>Jump for Joy Sale</h2>
</div>
<div id="main">
<div class="guess_box"><img src="images/jump1.jpg"/></div>
<div class="guess_box"><img src="images/jump2.jpg"/></div>
<div class="guess_box"><img src="images/jump3.jpg"/></div>
<div class="guess_box"><img src="images/jump4.jpg"/></div>
</div>
<script src="scripts/jquery-1.6.2.min.js"></script>
<script src="scripts/my_script.js"></script>
</body>
Jscript
$(document).ready(function()
{
$(".guess_box").click(checkForCode);
function checkForCode()
{
var code_box = 2;
var discount_code = getRandomNum(1,100);
var clicked = $(this); // debugger says clicked is an event object
var iteration = 0;
$(".guess_box").each(function()
{
if ($(this).context === $(clicked).context) //act like event objs
{
if (iteration === code_box)
{
// clicked on correct box
$(this).addClass("discount"); //same $(this) acts like <div>
discount_msg = "<p>Your Code: CODE"+ discount_code +"</p>";
return(false);
}
}
else
{
if (iteration === code_box)
{
// if wrong box clicked, highlight the right one
$(this).addClass("no_discount");
discount_msg = "<p>Sorry, no discount this time</p>";
return(false);
}
}
iteration += 1;
});
$(".guess_box").unbind();
$(this).append(discount_msg); // don't worry about this line
} //checkForCode
}); //ready
The context of this depends on where and how it's used. if your function is called by an an event it will refer to the target of the event, otherwise it will refer to the object being called upon.
What youre seeing in your console is not this, or an event object, it's a jQuery object. If you want to inspect this you need to remove the jQuery wrapper function.
console.log(this);
Event example..
<div>click me</div>
$("div").click(function(){
// referring to the div itself
$(this).text("you clicked me");
// Note you can do it without jQuery as well
// this.innerHTML = "you clicked me";
});
object example
function something(){
this.something = "something";
this.doAThing = function(){
this.something = "something new";
}
}
var thing = new something();
thing.doAThing();
alert(thing.something);
Thanks to those that responded. As Pamblam indicated, I was confusing this and $(this). I replaced 2 lines in my code and it makes more sense:
clicked = $(this) becomes clicked = this
if ($(this).context === $(clicked).context) becomes
if (this === clicked)

Using $(this) instead $('.article') in this code didn't work?

var main = function(){
$('.article').click(function(){
//$('.article').removeClass('current');
$(this).removeClass('current');
$('.description').hide();
$(this).addClass('current');
$(this).children('.description').show();
});
$('.article').dblclick(function(){
//$('.description').hide();
$(this).children('.description').hide();
});
};
$(document).ready(main);
This code is make a table arcodition like this http://www.codecademy.com/courses/web-beginner-en-4hxyb/0/5?content_from=make-an-interactive-website%3Ajquery-events click fullcreen you see that using $(this).removeClass('current') instead $('.article').removeClass('current'). this keyword that reference to the 'article' class why using like that it didn't reference to 'article' class, must using '.artilce'. Can someone explain it, thanks!
here you have a simplified code showing that it works
var main = function(){
$('.article').click(function(){
// below will change all with class article to green
// $('.article').addClass('green')
// with this it only changes the clicked one to green
//$(this).addClass('green');
// below will remove red-class from clicked .article
//$(this).removeClass('red');
//below will remove red-class from all elements with .article
$('.article').removeClass('red');
});
}; $(document).ready(main);
http://jsfiddle.net/tgLckfgz/2/

how to repeat same Javascript code over multiple html elements

Note: Changed code so that images and texts are links.
Basically, I have 3 pictures all with the same class, different ID. I have a javascript code which I want to apply to all three pictures, except, the code needs to be SLIGHTLY different depending on the picture. Here is the html:
<div class=column1of4>
<img src="images/actual.jpg" id="first">
<div id="firsttext" class="spanlink"><p>lots of text</p></div>
</div>
<div class=column1of4>
<img src="images/fake.jpg" id="second">
<div id="moretext" class="spanlink"><p>more text</p></div>
</div>
<div class=column1of4>
<img src="images/real.jpg" id="eighth">
<div id="evenmoretext" class="spanlink"><p>even more text</p></div>
</div>
Here is the Javascript for the id="firsttext":
$('#firstextt').hide();
$('#first, #firsttext').hover(function(){
//in
$('#firsttext').show();
},function(){
//out
$('#firsttext').hide();
});
So when a user hovers over #first, #firsttext will appear. Then, I want it so that when a user hovers over #second, #moretext should appear, etc.
I've done programming in Python, I created a sudo code and basically it is this.
text = [#firsttext, #moretext, #evenmoretext]
picture = [#first, #second, #eighth]
for number in range.len(text) //over here, basically find out how many elements are in text
$('text[number]').hide();
$('text[number], picture[number]').hover(function(){
//in
$('text[number]').show();
},function(){
//out
$('text[number]').hide();
});
The syntax is probably way off, but that's just the sudo code. Can anyone help me make the actual Javascript code for it?
try this
$(".column1of4").hover(function(){
$(".spanlink").hide();
$(this).find(".spanlink").show();
});
Why not
$('.spanlink').hide();
$('.column1of4').hover(
function() {
// in
$(this).children('.spanlink').show();
},
function() {
// out
$(this).children('.spanlink').hide();
}
);
It doesn't even need the ids.
You can do it :
$('.column1of4').click(function(){
$(this); // the current object
$(this).children('img'); // img in the current object
});
or a loop :
$('.column1of4').each(function(){
...
});
Dont use Id as $('#id') for multiple events, use a .class or an [attribute] do this.
If you're using jQuery, this is quite easy to accomplish:
$('.column1of4 .spanlink').hide();
$('.column1of4 img').mouseenter(function(e){
e.stopPropagation();
$(this).parent().find('.spanlink').show();
});
$('.column1of4 img').mouseleave(function(e){
e.stopPropagation();
$(this).parent().find('.spanlink').hide();
});
Depending on your markup structure, you could use DOM traversing functions like .filter(), .find(), .next() to get to your selected node.
$(".column1of4").hover(function(){
$(".spanlink").hide();
$(this).find(".spanlink, img").show();
});
So, the way you would do this, given your html would look like:
$('.column1of4').on('mouseenter mouseleave', 'img, .spanlink', function(ev) {
$(ev.delegateTarget).find('.spanlink').toggle(ev.type === 'mouseenter');
}).find('.spanlink').hide();
But building on what you have:
var text = ['#firsttext', '#moretext', '#evenmoretext'];
var picture = ['#first', '#second', '#third'];
This is a traditional loop using a closure (it's better to define the function outside of the loop, but I'm going to leave it there for this):
// You could also do var length = text.length and replace the "3"
for ( var i = 0; i < 3; ++i ) {
// create a closure so that i isn't incremented when the event happens.
(function(i) {
$(text[i]).hide();
$([text[i], picture[i]].join(',')).hover(function() {
$(text[i]).show();
}, function() {
$(text[i]).hide();
});
})(i);
}
And the following is using $.each to iterate over the group.
$.each(text, function(i) {
$(text[i]).hide();
$([text[i], picture[i]].join(', ')).hover(function() {
$(text[i]).show();
}, function() {
$(text[i]).hide();
});
});
Here's a fiddle with all three versions. Just uncomment the one you want to test and give it a go.
I moved the image inside the div and used this code, a working example:
$('.column1of4').each(function(){
$('div', $(this)).each(function(){
$(this).hover(
function(){
//in
$('img', $(this)).show();
},
function(){
//out
$('img', $(this)).hide();
});
});
});
The general idea is 1) use a selector that isn't an ID so I can iterate over several elements without worrying if future elements will be added later 2) locate the div to hide/show based on location relational to $(this) (will only work if you repeat this structure in your markup) 3) move the image tag inside the div (if you don't, then the hover gets a little spazzy because the positioned is changed when the image is shown, therefore affecting whether the cursor is inside the div or not.
EDIT
Updated fiddle for additional requirements (see comments).

Optimizing code to define variables only once, code only works when the vars are in change function and for the code outside change I redefine?

Pretty sure I know the solution... would write .on('change','load', function(){}
correct? <-- Tested didn't work? so I am up to your solutions :)
Sushanth -- && adeneo both came up with great solutions, this is a good lesson in optimizing code... It's gonna be hard to choose which answer to go with, but I know this is going to help me rethink how I write... I dont know what I do without this forum, id have to learn this stuff in college.
This is purely a question out of curiosity and bettering my skills, as well as giving you guys a chance to display your knowledge on jQuery. Also to prevent any sloppy writing.
I have a radio based switch box, the markup looks like this, the id's and on/off values are generated by the values in my array with PHP...
<span class="toggle-bg">//This color is the background of the toggle, I need jQuery to change this color based on the state on/off
<input type="radio" value="on" id="_moon_page_header_area1" name="_moon_page_header_area">//this is my on value generated by the array
<input type="hidden" value="_moon_page_header_area" class="switch-id-value">// I create this input because I have multiple checkboxes that have the ID _moon_ARRAYVALUE_area1
<input type="radio" value="off" id="_moon_page_header_area2" name="_moon_page_header_area">// off value
<input type="hidden" value="_moon_page_header_area" class="switch-id-value">//_moon_ARRAYVALUE_area2
<span class="switch"></span>// the switch button that changes
</span>
Hope that makes sense and the comments are clear
Here is the jQuery
var value = $('.toggle-bg input.switch-id-value').val()
var moon1 = $('#'+value+'1').is(':checked');
var moon2 = $('#'+value+'2').is(':checked');
var static_slide = $('._moon_staticarea_height');
var toggle = $('.toggle-bg');
if(moon1){
toggle.css({'background-color': '#46b692'});
static_slide.hide()
} else
if (moon2){
toggle.css({'background-color': '#333'});
static_slide.show()
}
$('.toggle-bg').change(function () {
var value = $('.toggle-bg input.switch-id-value').val()
var moon1 = $('#'+value+'1').is(':checked');
var moon2 = $('#'+value+'2').is(':checked');
var static_slide = $('._moon_staticarea_height');
var toggle = $('.toggle-bg');
if(moon1){
toggle.css({'background-color': '#46b692'});
static_slide.slideUp()
} else
if (moon2){
toggle.css({'background-color': '#333'});
static_slide.slideDown()
}
});
it looks longer than it really is, its just repeating it self, one is on load so that it gives the correct color on load of the page, and then inside the change function we need to change colors..
How do I write it so I only have to use variables one time (so its cleaner) is there a better way to optimize it... Just NOW thinking after writing this I could put it in one function .on('load', 'change', function() {}
I just now thought of that, but I wrote all this so I am going to see what others think...
You'd do that by having the function in the change event handler, and on the end you chain on a trigger('change') to make it work on pageload :
$('.toggle-bg').on('change', function () {
var value = $('.toggle-bg input.switch-id-value').val(),
moon1 = $('#' + value + '1').is(':checked'),
slider = $('._moon_staticarea_height'),
toggle = $('.toggle-bg');
toggle.css('background-color', (moon1 ? '#46b692' : '#333'));
slider[moon1?'slideUp':'slideDown']();
}).trigger('change');
As radiobuttons can't be unchecked, it's either moon1 or moon2, which means checking one of them should be enough.
.on('change','load',
supposed to be
// Remove the comma separator if you want to bind the same handler to
// multiple events.
.on('change load',
And you can remove the one separately written out and enclose it in a function (if multiple instances of the class toggle-bg)
or just trigger the change event.(If there is a single instance of a class)
This will just run the same functionality when the page loads.
var toggle = $('.toggle-bg');
toggle.change(function () {
var value = $('input.switch-id-value', this).val(),
moon1 = $('#' + value + '1').is(':checked'),
moon2 = $('#' + value + '2').is(':checked'),
static_slide = $('._moon_staticarea_height');
if (moon1) {
toggle.css({
'background-color': '#46b692'
});
static_slide.slideUp()
} else if (moon2) {
toggle.css({
'background-color': '#333'
});
static_slide.slideDown()
}
}).change();

Categories

Resources