Reputation:
Okay so, I recently started learning about async JS and APIs and fetch and am just creating a small project for practice and I want to add 2 more features to it
I want to add a button on which when clicked without refreshing the page, gives us a new GIF.
A search bar for the GIF we can find using that bar.
Here is my code:
<body>
<img src="#" />
<button>New Giffy</button>
<script>
const img = document.querySelector('img');
const btn = document.querySelector('button');
fetch(
`https://api.giphy.com/v1/gifs/translate?api_key=pH9WHztAm5Yt9v5VAziRzXhOBvblWf6m&s=akatsuki`, {
mode: 'cors'
}
)
.then((response) => {
return response.json();
})
.then((response) => {
img.src = response.data.images.original.url;
});
</script>
</body>
Upvotes: 1
Views: 3872
Reputation: 2416
you can provide onClick
on button which will call the function defined in below code or refer fiddle
<body>
<input type="text" placeholder="search here..." id="searchField" value="akatsuki">
<button onClick="onGifClick()">New Giffy</button><br>
<img src="#" />
<script>
function onGifClick() {
const search = document.querySelector('#searchField');
const img = document.querySelector('img');
const btn = document.querySelector('button');
debugger;
fetch(
`https://api.giphy.com/v1/gifs/translate?api_key=pH9WHztAm5Yt9v5VAziRzXhOBvblWf6m&s=` + search.value, {
mode: 'cors'
}
)
.then((response) => {
return response.json();
})
.then((response) => {
img.src = response.data.images.original.url;
});
}
onGifClick();
</script>
</body>
Upvotes: 1
Reputation: 327
This is pretty straight forward thing. But I will help you.
<body>
<img src="#" />
<button onclick="newGif()">New Giffy</button>
<script>
const img = document.querySelector('img');
const btn = document.querySelector('button');
function newGif(){
fetch(`https://api.giphy.com/v1/gifs/translate?api_key=pH9WHztAm5Yt9v5VAziRzXhOBvblWf6m&s=akatsuki`,{mode:'cors'})
.then((response) => response.json())
.then((response) => {
img.src = response.data.images.original.url;
});
}
newGif() //This is so a new gif is loaded as soon as the page loads
</script>
</body>
Upvotes: 0