easy way to assign function onclick - javascript - javascript

I am searching for much time now, for a very simple and effective way to aasign function on the click of a button in javascript (not jQuery).
The problems that I have are : 1.sometimes the dom is not yet created and the javascript function has undefined vars in it. 2.I can't pass in the right way attributes to this function.
So baically i have these:
<div class="container">
<button type=button class="click">Click</button>
<div class="smallContainer">
<img src="source.com" class="myimage">
<div class="data"> some data</div>
</div>
</div>
<div class="container">
<button type=button class="click">Click</button>
<div class="smallContainer">
<img src="source.com" class="myimage">
<div class="data"> other data</div>
</div>
</div>
<div class="container">
<button type=button class="click">Click</button>
<div class="smallContainer">
<img src="source.com" class="myimage">
<div class="data"> usefull data</div>
</div>
</div>
for (){ assign in each button the onclick function}
function onclick(){
here i want to change the opacity of the image by the class "myimage",
take the innerHTML of the div by the class "data" and do something to it(maybe i ll send an ajax request in this function also)
}
So I need a for loop or something (inside the javascript file maybe), that will asign to all buttons this function. I need every time I click the button, the function to know which button is and what the div by the class "data" has inside.
I tried many ways, each one had problems. Can anyone help with a simple working solution?
Thank you

Since you mention you do not have the skills to do this simple in plain JavaScript, then it is time to get jQuery added to your toolbox.
Here is about all the code you would need
$function() { // when the page is ready
$(".click").on("click", function(e) { // assign a function to ALL class="click"
var id = this.id; // or $(this).attr("id"); - if you need the button's ID
var divContent = $(this).parents().find(".data").html()
$.get("someserver.php",{"id":id,"parm":divContent},function(data) {
alert(data);// from server
});
});
});

try using jquery library :) with that yoy can do codes like
<script>
$(".data").click(function(){
var class_value = $(this).html();
})
</script>
as you can see, the function will be applied to all element having tha class "data"

Related

Script Revision for event.target

I'm kind of a newbie to js, could someone have a look at this code and tell me if it is correct and if it could be improved and how? it is working as intended, but honestly I don`t know if it is well written. Thanks in advance (:
<script>
$(document).ready(function() {
$("button").click(function(event) {
var a = (event.target).classList.item(0);
var b = ".carousel" + "." + a ;
$(b).myfunction;
});
});
</script>
The reason for that script is that I have a Carousel (Bootsrap) inside a Slider ("JQuery lightSlider") inside a custom popup modal and I don`t want the imgs carousel to load at page start only when the carousel would be visible.
What the script does is to "store" the class name of the button element ("custom-n") clicked, then write .carousel.custom-x to be stored in the variable b, and then use the var b as a selector to call the function for that custom-n carousel that replaces data-src with src.
I hope this isn't confusing haha
This is a simplification of the html, the modal opens whenever a <button> is clicked.
The are kind of a "thumbnail" for the main slider (light-slider), so:
<button class="custom-1"> opens the modal and set the "light-slider" to slide n1
<button class="custom-2"> opens the modal and set the "light-slider" to slide n2
and so on.
The carousels inside the lightslider's slides they all have img with data-src and the Idea is to replace the data-src with src of the carousel that should be "related" to the custom
<div class="light-slider-buttons">
<button class="custom-1 myclass"></button>
<button class="custom-2 myclass"></button>
<button class="custom-3 myclass"></button>
</div>
<div class="modal-wrp">
<div class="modal-inner">
<ul id="light-slider">
<li>
<div class="slide-wrapper">
<div class="carousel custom-1">
<div class="carousel-inner">
<div class="carousel-item active">
<img data-src="...">
</div>
<div class="carousel-item">
<img data-src="...">
</div>
<div class="carousel-item">
<img data-src="...">
</div>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
The code looks good.
I have two suggestions.
Firstly, you seem to be using class attribute to store data (custom-1, etc)
Why not set it to data-item-class attribute instead (any name starting with data- will do)?
<div class="light-slider-buttons">
<button class="myclass" data-item-class="custom-1"></button>
<button class="myclass" data-item-class="custom-2"></button>
<button class="myclass" data-item-class="custom-3"></button>
</div>
The value can be read as event.target.dataset.itemClass (item-class becomes itemClass, see docs for more info).
The code for variable a will be replaced with:
var a = event.target.dataset.itemClass;
Secondly, setting click event handler for 'button' selector is too wide.
It will cause errors when new button element with another purpose gets added to your page in the future.
It is much safer to think of <div class="light-slider-buttons"> as a component wrapping your button elements and apply the click handler only to those.
$(".light-slider-buttons button").click(function(event) {
...
}
It does not change much but is important because if you add other buttons outside <div class="light-slider-buttons"> they will not get click event handler.
jQuery uses CSS selectors syntax, you can find more in docs.
Here's the recommended code for script tag
<script>
$(document).ready(function() {
$(".light-slider-buttons button").click(function(event) {
var a = event.target.dataset.itemClass;
var b = ".carousel" + "." + a ;
$(b).myfunction;
});
});
</script>
P.S. jQuery programming style is quite imperative (specifying how page should update on every event).
There are other ways to build UI, for example in React programming is declarative (specifying how UI should look like based on given input/state)

Preload HTML from within Javascript file, into the DOM, but don't execute

Im creating a simple JS game, which will run in the browser and will pull the files directly from the pc. Because of this needed to make a workaround the "Cross-origin" error, which went smoothly, I put all the HTML within a JS and loaded the JS from the tag in the index.html. Everything was going smoothly so far.
You click "press any key to continue" -> but then next you click "New Game" and you get event listener error "can't set property of null". Which i don't understand how it happens, because the element is already in the "DOM" , the css could pick it up, but the event listener could not? So i tried moving all scripts on top, rearranging stuff, nothing worked. Pre-loading all HTML into the index.html, without executing it will definitely work, but how can i achieve this exactly? My Configuration atm is:
index.html (root folder)
/components/main_menu.js
/components/character_creation.js
function MainMenu()
{/*
<div id="mm_wrapper_grid">
<div id="mm_subgrid1">
</div>
<div id="mm_subgrid2">
<div id="mm_subgrid2_image"></div>
<div id="mm_new_game"><p id="mm_new_game_p" class="grow">New Game<p></div>
<div id="mm_load_game"><p id="mm_load_game_p" class="grow">Load Game</p></div>
<div id="mm_options"><p id="mm_options_p" class="grow">Options</p></div>
<div id="mm_credits"><p id="mm_credits_p" class="grow">Credits</p></div>
</div>
</div>
*/}
function CharacterCreation()
{/*
<div> Character Creation test
</div>
*/}
<div id ="game">
<div id="loading_screen">Press Any Key To Continue</div>
</div>
<script type="text/javascript">
document.getElementById("loading_screen").addEventListener("click", function() {callback("game", MainMenu)});
document.getElementById("mm_new_game_p").addEventListener("click", function() {callback("game", CharacterCreation)});
function callback(arg1, func)
{
var html = func.toString();
var htmlstart = html.indexOf('/*');
var htmlend = html.lastIndexOf('*/');
var html = html.substr(htmlstart+2, htmlend-htmlstart-2);
document.getElementById(arg1).innerHTML = html;
}
</script>
You have the problem because you are trying to add the second listener for getElementById("mm_new_game_p") when this element doesn't exist on the page. I suggest you to add the follwing line of code to make sure, that it's true:
<script type="text/javascript">
document.getElementById("loading_screen").addEventListener("click", function() {callback("game", MainMenu)});
console.log('#mm_new_game_p', document.getElementById("mm_new_game_p"));
document.getElementById("mm_new_game_p").addEventListener("click", function() {callback("game", CharacterCreation)});
...
You have to add this listener after this element will be created (after calling of MainMenu() function).
To tell the truth, I can see such storing of html templates in js functions for the first time. It's hard to support your code and I've modified it a little bit below. This is not the best way to implement it, but my goal is show you a solution based on your code. What you can see here:
all the templates for pages are in html (not in JS);
you can add listeners from html code using HTML attribute onclick - and in this case you can be sure, that element exists on the page.
If you want to add listeners from JS, than you have to create own functions for each pages which you have and after HTML template of a page will be added to #game container you will need to create event listeners for the buttons which are on the created page.
openPage("game", "loading_screen");
function openPage(parentDOMElementId, name) {
console.log('openPage:', name);
var pageHtml = document.getElementById("page_" + name).outerHTML;
document.getElementById(parentDOMElementId).innerHTML = pageHtml;
}
<div id="game"></div>
<div class="templates" style="visibility: hidden;">
<div id="page_loading_screen" onclick="openPage('game', 'main_menu')">
Press Any Key To Continue
</div>
<div id="page_main_menu">
<div id="mm_subgrid1">
</div>
<div id="mm_subgrid2">
<div id="mm_subgrid2_image"></div>
<div id="mm_new_game">
<p id="mm_new_game_p" class="grow" onclick="openPage('game', 'character_creation')">New Game
<p>
</div>
<div id="mm_load_game">
<p id="mm_load_game_p" class="grow">Load Game</p>
</div>
<div id="mm_options">
<p id="mm_options_p" class="grow">Options</p>
</div>
<div id="mm_credits">
<p id="mm_credits_p" class="grow">Credits</p>
</div>
</div>
</div>
<div id="page_character_creation">
Character Creation test
</div>
</div>

Add element in Handlebar

I have handlebar.js integration and I am populating a number of dropdowns using the template. Now I need to have a button which needs to add the same elements below. The code is like this
<div class='row'>
//my HTML goes here
<button>Add One more</button>
</div>
When I click on the Add One more button it needs to clone the div with class name row and needs to add it to the next line. How can I do this using Handlebars? Or I need to use jQuery here?
Don't know handlebars.js, but with jQuery it'll be preety simple:
$(document).on('click', '.row button', function() {
var cloned = $(this).closest('.row').clone();
$(this).closest('.row').parent().append(cloned);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="row">
other stuff
<button>add one</button>
</div>
</div>

Fire onclick event based on class of another div?

I have a javascript button that fires an onclick event but i only want it to do that if another div contains a class called "active".
so I have this structure:
<div id="div1">
<div id="someid1" class="design"></div>
<div id="someid2" class="design"></div>
<div id="someid3" class="design"></div>
<div id="someid4" class="design"></div>
</div>
that based on other page activity any can change to class="active"
<div id="someid2" class="design active">
The button is:
<button type="button" id="button1" onclick="dosomething">Click me</button>
but i only want the dosomething to work if the above any of the divs has the active class, and throw an alert if it does not. I am not terribly good with javascript and could use some help.
Hope this is clear. Thanks.
Assuming dosomething is a function, you could just check for the class inside it
function dosomething() {
if ( document.querySelector('#parentid .active') ) {
// do stuff
}
}
querySelector returns null if not found, which is falsy.
document.querySelector documentation

How to get a value from div without write some event (onclick,etc) using jquery

I have some question about how to get some value from some element like div,etc using jquery and without write onclick event or etc on the div where I want to get that value.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="test" title="test1">test</div>
<div id="test2" title="test2">test2</div>
<script>
function getVal(attr,value){
$("#show").text("this "+attr+" have value ="+value);
}
$(document).ready(function(){
$("#test").click(function(){
getVal("#test",$("#test").attr("title"));
});
});
</script>
<div id="show"></div>
</body>
</html>
Usually to get some value from div that i click, I add an onclick event on div like
<div id='test' onclick="getVal(test)" ></div>
and it will return "test". And the code that I write above nearly what I want, but the problem that I have is if I have a many div, how can I get the value from each div that I click just using jquery click function and I don't need to write
$("#test").click(function(){
getVal("#test",$("#test").attr("title"));
});
$("#test2").click(function(){
getVal("#test2",$("#test2").attr("title"));
});//and so on
here the code that I use to achieve what I want, using onclick event that I put on div:
<script type="text/javascript">
function overlay(rel){
var value = rel;
$(document).ready(function(){
$(".img"+value).click(function(){
$(".overlay-bg"+value).fadeIn();
});
$(".close"+value).click(function(){
$(".overlay-bg"+value).fadeOut();
})
});
}
</script>
<div id="gallery">
<img src="http://localhost/wedding/source/gallery/thumb/thumb-a.jpg" class="img1" onclick="overlay(1)" title="photo1" alt="photo1"/>
</div>
<div id="overlay-bg" class="overlay-bg1">
<div id="overlay"><img src="http://localhost/wedding/source/gallery/a.jpg"/>
<span>photo1</span>
<span style="font-size:0.8em;"><p>photo a</p></span>
<div id="close" class="close1"></div>
</div>
</div>
<div id="gallery">
<img src="http://localhost/wedding/source/gallery/thumb/thumb-b.jpg" class="img2" onclick="overlay(2)" title="photo2" alt="photo2"/>
</div>
<div id="overlay-bg" class="overlay-bg2">
<div id="overlay"><img src="http://localhost/wedding/source/gallery/b.jpg"/>
<span>photo2</span>
<span style="font-size:0.8em;"><p>photo b</p></span>
<div id="close" class="close2"></div>
</div>
</div>
I'm really want to know how to resolve my problem.
Give the elements you want to attach the click event handler to the same class. Then use the class selector [docs] to select all of them:
$('.sharedClass').click(function() {
getVal(this.id, $(this).attr("title"));
});
jQuery will bind the event handler to each of the selected elements.
There are many ways to select elements [docs], selection by ID or class are just two of them. You might also find the jQuery tutorial useful to get a better idea of how jQuery works.
you can use the this keyword within the handler function, and it will point to the element that was clicked
Here's the correct way to do it.
Put a class name to your target div e.g.
<div id="test" class="clickable" title="test">test</div>
<div id="test2" class="clickable" title="test">test</div>
...
...
Then create a jQuery event with selected class
$('.clickable').click(function(){ ... });
<div id="test">harsh</div>
<script>
alert(document.getElementById('test').innerHTML);
</script>
If you want to call this function with the click of every div, use :
$("div").click(function(){
getVal($(this),$(this).attr("title"));
});
If you want to call the function for a set of divs, but not all, give those divs a class name as suggested by #Felix Kling.
Check out the jQuery Selectors to get a better idea.
Not sure what you're trying to achieve.
If you have multiple values how do you want to store them?
If you have an array that you wanted to populate you can use the each() function on a JQuery selector to traverse all elements selected.
Like so:
var values = new Array();
$(document).ready(function(){
$('#test1, #test2').each(function(){
values.push($(this).html());
});
});
You could also store the values in an associative way to make retrieval a bit easier if you didn't want to iterate through an array. For example you could use the value of the 'title' attribute as the key in the array.
Replace the values.push() line with this line of code:
values[$(this).attr('title')] = $(this).html();

Categories

Resources